簡體   English   中英

通過Spring REST API用Angular 2下載的文件大小是原來的兩倍。 為什么?

[英]Files downloaded with Angular 2 over Spring REST API are twice size. Why?

我想從angular 2下載文件。我的問題是,我從Spring REST API獲得的所有文件都是文件大小的兩倍。

角度片段:

return this.authHttp.get(this.restAPI + '/downloadFile/' + fileId)
         .toPromise()
             .then(response => {
                //  var arrayBufferView = new Uint8Array( response.arrayBuffer() );
                //  var blob = new Blob( [ arrayBufferView ], { type: response.headers.get("Content-Type") } );
                //  return blob;

                 return new Blob([response.arrayBuffer()], { type: response.headers.get("Content-Type")})
                })

            .catch(this.handleError);

春季REST片段:

@RequestMapping(value = "/downloadFile2/{fileId}",
        method = RequestMethod.GET)
public void downloadFileHandler2(@RequestHeader("Authorization") String token, 
        @PathVariable String fileId, HttpServletResponse response) throws IOException {

    changeToCustomerDataBase(token);

    File file = projectService.readFromDB(fileId);

    response.addHeader("Content-Disposition", "attachment; filename="+file.getName());
    response.setContentType(Files.probeContentType(file.toPath()));
    response.setContentLengthLong(file.length());

    FileInputStream fis = new FileInputStream(file);
    int c; 
    while((c = fis.read()) > -1) {
        response.getOutputStream().write(c);    
    }

    response.flushBuffer();

    fis.close();
}

來自數據庫的文件具有原始大小。

怎么了? 我忘記了什么嗎? 非常感謝您的幫助。

昨天我遇到了同樣的問題並解決了。 希望您或其他任何人都可以使用該解決方案。 responseType: ResponseContentType.Blob添加到您使用的authHttp.get的authHttp.get

let requestOptions: RequestOptionsArgs = {
        ...,
        responseType: ResponseContentType.Blob
};
.
.
.
return this.http.request(path, requestOptions);

然后使用response.blob()而不是new Blob([response.arrayBuffer()], { type: response.headers.get("Content-Type")})

對我來說,那很奏效。 希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM