2017-08-29 50 views
0

我的Web應用程序運行Tomcat 8. .docx文件已正確上載到服務器,並使用jsp中包含的以下Java代碼進行下載。Java下載通過添加一個字符損壞.docx文件

File f = new File (Monitor.getPropertyValue("myDir") + (request.getParameter("file"))); 

    String filename=request.getParameter("original"); 
    response.setContentLength((int) f.length()); 
    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document"); 

    response.setHeader ("Content-Disposition", "attachment; filename="+filename); 
    InputStream in = new FileInputStream(f); 
    ServletOutputStream outs = response.getOutputStream(); 


    int bit = 256; 
    int i = 0; 
    try { 
    while ((bit) >= 0) { 
    bit = in.read(); 
    outs.write(bit); 
        } 
     } 
     catch (IOException ioe) { 
       ioe.printStackTrace(System.out); 
      } 
    outs.flush(); 
    outs.close(); 
    in.close(); 

然而,當我嘗試打開下載的文件,它已損壞,Word將不能打開它(沒有首先確定它)

當我比較原始文件和下載的文件,然後我注意到,下載的文件在最後有一個額外的字符 - FF(十六進制)

如果我用十六進制編輯器刪除這個額外的字符,那麼文件打開罰款。

爲什麼要添加這個額外的字符?

+0

你不應該使用'JSP'下載的二進制文件。改寫一個servlet。 – Xvolks

+0

我知道 - 這是我沒寫的舊代碼。你認爲這是問題的根源,還是你只是提出了良好的編程習慣? – gordon613

+0

最佳做法。過去我已經做過這樣醜陋的事情,並且我學會了不這樣做的艱難方式。 – Xvolks

回答

4

您的循環錯誤。最後的實際字節寫入後,bit仍含有它,進入循環,in.read()讀取-1並將其寫出,導致額外的0xFF(即-1)字節。

更改您的循環來檢查寫出來之前,什麼內容如下

while((bit = in.read()) != -1) { 
    outs.write(bit); 
}