2017-03-27 77 views
1

我在使用angular2從spring啓動下載文件時出現問題。春季啓動Angular2文件下載不起作用

這是我的代碼從春季啓動,它來自:Return generated pdf using spring MVC。我可以dirrectly下載文件,郵遞員,但不能與angular2 ...

@RequestMapping(value="/file/{id}", method=RequestMethod.GET) 
public ResponseEntity<?> getFile(@PathVariable("id") long id) { 
    UploadFile uFile = uploadFileService.getUploadFileById(id); 


    byte[] contents = uFile.getContent(); 

    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.parseMediaType("application/pdf")); 
    headers.setContentDispositionFormData(uFile.getName(), uFile.getName()); 
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); 

    return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK); 
} 

Angular2服務

downloadFile(id: number){ 
    let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'}); 
    headers.append('Authorization',this.auth.token); 
    let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob}); 

    return this.http.get(this.editUrl + id, options) 
    .map(res => {return new Blob([res.blob()],{ type: 'application/pdf' })}); 
} 

和下載按鈕

downloadFile(uFile: UploadFile){ 
    this.uploadFileService.downloadFile(uFile.id) 
     .subscribe(
       data => window.open(URL.createObjectURL(data)), 
      ); 
    return false; 
} 

當我點擊下載按鈕打開Chrome瀏覽器新標籤頁,立即關閉它不顯示任何文件。 這裏是郵差的一些響應標題。

Access-Control-Allow-Headers →Content-Type, x-requested-with, Authorization, responseType 
Access-Control-Allow-Methods →POST, PUT, GET, PATCH, OPTIONS, DELETE 
Access-Control-Allow-Origin →http://localhost:4200 
Access-Control-Max-Age →3600 
Cache-Control →must-revalidate, post-check=0, pre-check=0 
Content-Disposition →form-data; name="reference.pdf"; filename="reference.pdf" 
Content-Length →31576 
Content-Type →application/pdf 
Date →Mon, 27 Mar 2017 08:39:24 GMT 
X-Content-Type-Options →nosniff 
X-Frame-Options →DENY 
X-XSS-Protection →1; mode=block 
+1

看看這兩個答案,我寫了這個:http://stackoverflow.com/questions/37046133/pdf-blob-is-not-showing-content-angular-2/39657478#39657478和http:///stackoverflow.com/questions/40300252/angular2-displaying-pdf/40300966#40300966 –

+1

是的那些是我在解決方案中使用的完全代碼,但問題仍然存在。當我嘗試在IE中下載文件時,它會打開新標籤頁白色鏈接,如:blob:8ASDA017-7456B-4614-AD56-47456456021 – user3551808

+1

它不適用於IE,僅在Chrome和Mozilla中就我所知。 –

回答