我使用角来下载大文件,对于后端我使用spring引导,下面是端点的代码:
@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但是,当我尝试使用角下载文件时,它不起作用,即使请求成功,而且我可以在日志中看到文本“附加到文件”多次显示,但浏览器上没有下载任何内容,下面是我的代码:
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()属于文件保护程序,当我尝试以字节不流的形式下载文件时,上述代码可以工作。
我在互联网上所能找到的就是这个代码,它使用的是angularJs,而我使用的是角5,任何人都能指出这个问题吗?谢谢。
更新
我可以看到文件被下载在Google的网络选项卡中,但是我不知道文件被保存在哪里。

发布于 2018-11-22 11:09:01
似乎我错过了标题,在保存的同时,这是最后的版本,它可能会帮助其他人:
弹簧启动
将这些配置添加到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);
}发布于 2018-11-19 15:09:43
我试过使用您的后端代码,但在角度上我使用了以下方法:
window.location.href = "http://localhost:9001/rest/api/analyses/download";它开始成功地下载。
https://stackoverflow.com/questions/53366704
复制相似问题