2016-03-01 44 views
0

嘗試使用RestFul下載文件時出現問題。我正在設置Content-Disposition和附件,但是當文件被下載時,它有一個隨機名稱。使用REST下載文件時文件名錯誤

@GET 
@Path("{type}/xls") 
@Produces("application/vnd.ms-excel") 
public Response downloadExcel(@Context HttpHeaders headers...) { 
... 
File file = getFileToDownload(); 
Response.ResponseBuilder builder = Response.ok(file); 
    String fileName = file.getName(); 
    builder.header("Content-Disposition", "attachment; filename=" + fileName); 
... 
return builder.build(); 

例如,如果文件名是 「file001.xls」 的迴應是:

Response-Code: 200 
Content-Type: application/vnd.ms-excel 
Headers: {Content-Disposition=[attachment; filename=file001.xls], Content-Type=[application/vnd.ms-excel], Date=[Tue, 01 Mar 2016 16:18:19 GMT]} 

但下載的文件被命名爲這樣的: 8fecd36a-a5aa-4b04-B757 -4c38ddea11db.xls

請問您能幫助我嗎? :-)

+0

你用什麼客戶端下載? –

+0

我正在使用Java(Spring和AngularJS),並且問題發生在Firefox,Chrome和Safari中。謝謝! – amd

+0

代碼示例在http://stackoverflow.com/questions/4377589/how-do-i-send-a-file-with-jax-rs在文件名周圍有雙引號...... –

回答

0

我解決了我的問題。我已經添加了這個頭的響應:

builder.header("Access-Control-Expose-Headers", "Content-Disposition"); 

和檢索在客戶以這種方式迴應:

var contentDisposition = response.headers('Content-Disposition'); 
var initName = contentDisposition.indexOf('filename=') + 9; 
var fileName = contentDisposition.substring(initName); 

var blob = new Blob([response.data], {type: type}); 
var blobURL = URL.createObjectURL(blob); 
var anchor = document.createElement("a"); 
anchor.download = fileName; 
anchor.href = blobURL; 
anchor.click(); 
相關問題