春季启动:下载压缩的大文件,然后在服务器上对其进行处理

时间:2018-11-15 11:04:53

标签: java azure spring-boot download timeout

在我的应用中,我先压缩然后下载大文件,这些文件位于azure中,所以我从流中读取文件,然后将它们一个个地压缩,因此我可以在所有文件都保存完后下载zip文件被压缩,这是我的代码:

@RequestMapping(value = "{analyseId}/download", method = RequestMethod.GET, produces = "application/zip")
public ResponseEntity<Resource> download(@PathVariable List<String> paths) throws IOException {

    String zipFileName = "zipFiles.zip";
    File zipFile = new File(zipFileName);
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);
    for (String path : paths) {
        InputStream fis = azureDataLakeStoreService.readFile(path);
        addToZipFile(path , zos, fis);
    }
    zos.close();
    fos.close();
    BufferedInputStream zipFileInputStream = new BufferedInputStream(new FileInputStream(zipFile.getAbsolutePath()));
    InputStreamResource resource = new InputStreamResource(zipFileInputStream);
    zipFile.delete();

    return ResponseEntity.ok()
            .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + zipFileName)
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);
}

private static void addToZipFile(String path, ZipOutputStream zos, InputStream fis) throws IOException {
    ZipEntry zipEntry = new ZipEntry(FilenameUtils.getName(path));
    zos.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }
    zos.closeEntry();
    fis.close();
}

但是,在天蓝色的情况下,请求超时设置为230秒,cannot be changed,但是对于大文件而言,将其加载到服务器上然后将文件压缩后花费的时间要多得多,因此与客户端的连接将同时迷路。

所以我的问题是,因为我要从流中获取数据,我们可以同时进行所有这些操作吗,意味着获取流并同时下载它,而不必等到获取整个文件,或者是否有任何文件其他想法可以在这里分享。

谢谢。

1 个答案:

答案 0 :(得分:0)

答案是不将文件下载到服务器,然后将其发送到客户端,而是直接将其流式传输到客户端,这是代码

@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download(@PathVariable String path) throws IOException {

    final InputStream fecFile = azureDataLakeStoreService.readFile(path);
    return (os) -> {
        readAndWrite(fecFile, os);
    };
}

private void readAndWrite(final InputStream is, OutputStream os)
        throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) >= 0) {
        os.write(data, 0, read);
    }
    os.flush();
}

我还将此配置添加到ApplicationInit:

@Configuration
public static class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(-1);
        configurer.setTaskExecutor(asyncTaskExecutor());
    }

    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        return new SimpleAsyncTaskExecutor("async");
    }

}
相关问题