Angular不会从流中下载文件(StreamingResponseBody)

时间:2018-11-19 00:01:30

标签: angular download inputstream outputstream

我正在使用angular下载大文件,对于后端,我正在使用spring boot,这是端点的代码:

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

    final InputStream file =azureDataLakeStoreService.readFile(path);
    return (os) -> {
        readAndWrite(file , 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) {
        System.out.println("appending to file");
        os.write(data, 0, read);
    }
    os.flush();
}

当我尝试使用curl获取文件时,它可以工作,并且可以看到文件正在下载并且文件的大小在增加:

curl -H "Authorization: Bearer <MyToken>" http://localhost:9001/rest/api/analyses/download --output test.zip

但是,当我尝试使用angular下载文件时,即使请求成功,也无法正常工作,并且在日志中可以看到多次显示“ append to file”的文本,但是没有下载任何内容浏览器,这是我的代码:

this.http.get(url, { headers: headers, responseType: 'blob', observe: 'response' })
    .subscribe(response => {
        const contentDispositionHeader: string = response.headers.get('Content-Disposition');
        const parts: string[] = contentDispositionHeader.split(';');
        const filename = parts[1].split('=')[1];
        const blob = new Blob([response.body], {
            type: 'application/zip'
        });
        saveAs(blob, filename);
    });

saveAs()属于file-saver,顺便说一下,当我尝试将文件下载为byte []时(没有流式传输),上述代码起作用。

我在互联网上能找到的就是这个code,它在我使用angular 5时正在使用angularJs,有人可以指出这个问题!谢谢。

更新

我可以在Google chrome的“网络”标签中看到该文件正在下载,但是我不知道文件的保存位置。

enter image description here

2 个答案:

答案 0 :(得分:1)

我尝试使用您的后端代码,但在角度上,我使用了此代码:

window.location.href = "http://localhost:9001/rest/api/analyses/download";

它开始成功下载。

答案 1 :(得分:1)

似乎我错过了带有标头的arround,在保存时,这是最终版本,可能会帮助其他人:

Spring Boot

将这些配置添加到 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");
    }

}

这要交给您的控制器:

@RequestMapping(value = "{analyseId}/download", method = RequestMethod.GET, produces = "application/zip")
public ResponseEntity<StreamingResponseBody> download(@PathVariable Long analyseId) throws IOException {
    try {
        Analyse analyse = analyseService.getAnalyse(analyseId);

        final InputStream file =azureDataLakeStoreService.readFile(analyse.getZippedFilePath());
        Long fileLength = azureDataLakeStoreService.getContentSummary(analyse.getZippedFilePath()).length;
        StreamingResponseBody stream = outputStream ->
                readAndWrite(file , outputStream);

        String zipFileName = FilenameUtils.getName(analyse.getZippedFilePath());
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + zipFileName)
                .contentLength(fileLength)
                .contentType(MediaType.parseMediaType("application/zip"))
                .body(stream);
    } catch (Exception e) {
        e.printStackTrace();
        return ExceptionMapper.toResponse(e);
    }
}

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();
}

角度

download(id) {
    let url = URL + '/analyses/' + id + '/download';
    const headers = new HttpHeaders().set('Accept', 'application/zip');
    const req = new HttpRequest('GET', url, {
        headers: headers,
        responseType: 'blob',
        observe: 'response',
        reportProgress: true,
    });
    const dialogRef = this.dialog.open(DownloadInProgressDialogComponent);
    this.http.request(req).subscribe(event => {
        if (event.type === HttpEventType.DownloadProgress) {
            dialogRef.componentInstance.progress = Math.round(100 * event.loaded / event.total) // download percentage
        } else if (event instanceof HttpResponse) {
            dialogRef.componentInstance.progress = 100;
            this.saveToFileSystem(event, 'application/zip');
            dialogRef.close();
        }
    });
}

private saveToFileSystem(response, type) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition');
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    const blob = new Blob([response.body], {
        type: type
    });
    saveAs(blob, filename);
}