java restful文件传输_从RestFul Java Spring后端下载角文件

I have a situation where I want to download a large file from my RestFul java backend.

The java backend will stream the file in chunks see following code:

String filePath = this.workProgressService.getFilePath(entityId);

Path path = Paths.get(filePath);

FileNameMap fileNameMap = URLConnection.getFileNameMap();

String mimeType = fileNameMap.getContentTypeFor(path.getFileName().toString());

if (mimeType == null) {

mimeType = "application/octet-stream";

}

response.setContentType(mimeType);

response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", path.getFileName().toString()));

FileCopyUtils.copy(Files.newInputStream(path), response.getOutputStream());

The service is working fine. F.E. when I go in the browser to my restendpoint http://localhost:8080/download a file window popup and I can download the file.

But when I do this from angular with the following code:

const options = new RequestOptions({responseType: ResponseContentType.Blob});

return this.authHttp.get(this.configurationService.getApiURL() + '/filedownload', options)

.map(response => {

console.log(response.blob());

});

The console log of the blob is triggered at the end when the file is completely downloaded. If I watch the request in the developer console of Chrome I can see it download the whole file first before it will log it's response. This way the file save dialog is not opened untill the response is there.

The problem is I can't just use a href to the location of the Rest endpoint because I need to send an authorization header in the GET request.

How can I solve this that the user can download the file with a dialog from the back-end directly and not have to wait till browser has completely downloaded the file?

解决方案

The problem is solved.

The GET request of angular will trigger the filesaver dialog when the whole get request is completed. When downloading a large file this is not ideal because it will be downloaded in the browsers memory.

Because I have to use an authorization token which normally is in the header I had to create a workaround.

The workaround is indeed using the window.location.href with the RESTful endpoint to download. But before going to this endpoint the restful backend is called to create a short to live token which is valid to download a file.

This token is appended to the URL for the location.href.

Now the browser handles the file dialog to save the file on the computer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值