2017-02-17 50 views
0

我的用例是讓我的應用程序從服務器上下載一個excel(.xls)。 Excel應該有圖表。傳輸excel文件時數據丟失,如彈出式響應

這裏是它

@RequestMapping(value="/downloadExcel", method=RequestMethod.GET) 
public void download(HttpServletRequest request, HttpServletResponse response) { 

    String fileName = "excel.xls"; 
    response.setContentType("APPLICATION/vnd.ms-excel"); 
    response.addHeader("Content-Disposition", "attachment; filename=" + fileName); 
    try { 
     Files.copy(new File(fileName), (OutputStream)response.getOutputStream()); 
     response.getOutputStream().flush(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

服務器端代碼當您打開Excel中,我得到一個警告消息說「文件錯誤:數據可能已丟失」。而且,我看不到下載的Excel中的圖表。

我還檢查了將內容類型設置爲'OCTET-STREAM'但沒有運氣。

response.setContentType("APPLICATION/OCTET-STREAM"); 

如何轉移而不會丟失數據的Excel文件?

+0

你可以在一些地方上傳的文件,所以我可以嘗試下載相同的,並檢查是否得到同樣的錯誤? – cralfaro

回答

0

我用這個代碼,我可以下載Excel文件的圖形

void copyFileToResponse(HttpServletResponse response, File file) throws IOException { 
     if(file != null) { 
      String mimeType = URLConnection.guessContentTypeFromName(file.getName()); 
      if (mimeType == null) { 
       logger.debug("mimetype is not detectable, will take default"); 
       mimeType = "application/octet-stream"; 
      } 
      logger.debug("mimetype : {}", mimeType); 
      response.setContentType(mimeType); 
      response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); 
      response.setContentLength((int) file.length()); 
      InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 
      FileCopyUtils.copy(inputStream, response.getOutputStream()); 
     } 
    }