2017-08-17 724 views
0

我試圖從服務器上使用spring下載一個xlsx文件。文件獲取下載,但它顯示一個警告文件已損壞!爲什麼從服務器下載Excel(xlsx)文件後,文件已損壞,無法打開?

這裏是我的代碼:

File file = new File(outputPath+ fileName); 
FileInputStream fis = new FileInputStream(file); 
response.setContentType("application/vnd.openxmlformats- 
officedocument.spreadsheetml.sheet"); 
response.setContentLength((int) file.length());   
response.setHeader("Content-Disposition", "attachment; filename="+fileName); 
FileCopyUtils.copy(fis, response.getOutputStream()); 

JSP頁面:

$("#download").click(function(){ 
    if($(this).data('clicked', true)){ 
    window.location="http://localhost:8080/IRI-AXCO/downloadFile"; 
    } 
} 

這裏是快照:

enter image description here

幫助表示讚賞!由於

+0

顯示完整的控制器方法。 –

+0

嗨,我得到了解決方案,我將contenttype更改爲CSV格式',謝謝你的回覆 –

回答

0

我自己找到了解決辦法,

@GetMapping("/downloadFile") 
    public void download(HttpServletRequest request, HttpServletResponse response)throws Exception{ 
     try { 
      fileName=fileName.replace(" ", "_"); 
      File file = new File(outputPath+ fileName); 
      FileInputStream fis = new FileInputStream(file); 
      Path source = Paths.get(outputPath+ fileName); 
      String contentType=Files.probeContentType(source); 
      response.setContentType(contentType); 
      response.setContentLength((int) file.length()); 
      response.setHeader("Content-Disposition", "attachment; filename="+fileName); 
      FileCopyUtils.copy(fis, response.getOutputStream()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      throw e; 
     } 
    } 

上面的代碼給我的結果!