2016-09-29 108 views
0
  1. 我試圖從服務器中存在的固定位置下載zip文件。
  2. 在我Rest方法中,我只是從客戶端(瀏覽器)傳遞文件名。 (請參閱下面的代碼)。
  3. 在我Rest方法中,我將zip文件發送給客戶端。在Chrome中通過Java下載zip文件時沒有.zip擴展名

  4. 該文件在瀏覽器中下載沒有任何問題。

我的問題是,壓縮文件在沒有.zip擴展名的瀏覽器上下載。

@RequestMapping(value = "/zip/{filePath}", method = RequestMethod.GET) 
public @ResponseBody void downloadZip(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { 

    ServletContext context = request.getServletContext(); 
    File downloadFile = new File(filePath); 
    FileInputStream inputStream = new FileInputStream(downloadFile); 
    // get output stream of the response 
    OutputStream outStream = response.getOutputStream(); 

    byte[] buffer = new byte[(int) downloadFile.length()]; 
    int bytesRead = -1; 

    // write bytes read from the input stream into the output stream 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
    outStream.write(buffer, 0, bytesRead); 
    } 
    // get MIME type of the file 
    String mimeType = context.getMimeType(fullPath); 
    if (mimeType == null) { 
    // set to binary type if MIME mapping not found 
    mimeType = "application/octet-stream"; 
    } 
    System.out.println("MIME type: " + mimeType); 

    // set content attributes for the response 
    response.setContentType(mimeType); 
    response.setContentLength((int) downloadFile.length()); 

    response.setHeader("Content-Disposition", 
     String.format("attachment; filename=\"%s\"", downloadFile.getName())); 
    logger.error("Filename = " + downloadFile.getName()); 
    inputStream.close(); 
    outStream.close(); 
} 

PS:該文件被下載到某些機器上使用ZIP和某些沒有ZIP的機器上。我僅在Chrome上進行了測試(根據客戶要求)。 我認爲,Chrome設置存在問題,我需要關注(只是猜測)。

有人可以幫助嗎?

在此先感謝....

+2

更改設置響應頭文件和將文件推送到輸出流之間的順序 - 畢竟頭文件需要先離開。 –

+0

嘗試過,但它不起作用。不管怎麼說,多謝拉。 – krohit

+0

嘗試MIME類型「應用程序/郵編,應用程序/八位字節流」 –

回答

1

更改設置響應頭和推搡的文件下來輸出流之間的順序 - 畢竟,頭需要先離開。

將帖子

  1. 「爲什麼在開始效果碼設置HttpServletResponse的」。
    嗯,很簡單:客戶端應該通過解釋HTTP響應頭來接收關於如何處理有效內容的指令。如果一開始沒有設置,那麼在傳輸結束時發送這些頭文件就太遲了。假設HttpServletResponse實際上會在用setHeader調用時發送這些頭文件,這是一個很大的假設 - 我懷疑這些頭文件實際上不會發送到之後調用response.getOutputStream - 響應不太可能緩衝整個有效內容以等待調用者指定這些標題。
+0

這很好用!現在,我有一個關於這種行爲的問題。 1)爲什麼設置HttpServletResponse開始影響代碼。 2)爲什麼這在一些機器上工作,並不適用於某些機器(舊代碼)。 – krohit

+0

2.「爲什麼這在某些機器上運行,並且在某些機器(舊代碼)上不起作用。」 我不確定我是否理解這個問題:您在考慮什麼機器:不同的服務器機器或不同的客戶機處理下載請求? –

+0

謝謝你的回答,阿德里安。通過機器,我的意思是不同的客戶端處理下載。 (先生,我應該指定)。因此,我來​​到鉻問題的結論(具體設置改變也許....) – krohit