2017-08-17 722 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; 
     } 
    } 

上面的代码给我的结果!