2017-08-16 135 views
0

我需要从输出路径下载excel文件,但我无法这样做。如何使用Jquery和Spring Controller从服务器下载文件?

这里是我的jQuery代码

$("#download").click(function(){ 
    if($(this).data('clicked', true)){ 
     $.ajax({ 
       type:'POST', 
       url :"downloadFile", 
       contentType : "application/json; charset=utf-8", 
       success: function(result) { 
        alert('File Download'); 
       }, 
       error:function(exception){ 
        alert('Error Occured during file Download'); 
        console.log('exception',exception); 
       } 
      }); 
    } 
}); 

这是我的控制器代码:

@PostMapping("downloadFile") 
    @ResponseBody 
    public void downloadResult(HttpServletRequest request, HttpServletResponse response)throws Exception{ 
     try { 

      File file = new File(outputPath + fileName); 

      if (file.exists()) { 
       String mimeType = context.getMimeType(file.getPath()); 
       System.out.println(); 
       if (mimeType == null) { 
        mimeType = "application/octet-stream"; 
       } 

       response.setContentType(mimeType); 
       response.addHeader("Content-Disposition", "attachment; filename=" + fileName); 
       response.setContentLength((int) file.length()); 

       OutputStream os = response.getOutputStream(); 
       FileInputStream fis = new FileInputStream(file); 
       byte[] buffer = new byte[4096]; 
       int b = -1; 

       while ((b = fis.read(buffer)) != -1) { 
        os.write(buffer, 0, b); 
       } 

       fis.close(); 
       os.close(); 
      } else { 
       System.out.println("Requested " + fileName + " file not found!!"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      throw e; 
     } 

我需要它出现在浏览器中下载或保存选项的弹出。

帮助表示赞赏,感谢

UPDATE:

我无法打开该文件,请查看下面的图像。

enter image description here

所做的更改按照#StanislavL答案

控制器:

@GetMapping("/downloadFile") 
    public void downloadResult(HttpServletRequest request, HttpServletResponse response)throws Exception{ 
//CODE 
} 

JSP页面(JavaScript)的

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

你会得到什么错误?请通过网址为“/ downloadFile” –

+0

其实这就是我需要下载的Excel文件,所有的Excel数据都在浏览器控制台 –

回答

0

映射应该从/

启动

更改映射到@PostMapping("/downloadFile")

也不需要AJAX调用。你可以使用正常的GET映射,只需设置window.location = TheURL

+0

嗨,我已经按照你的说法做了,但我无法打开文件,它的显示结果为 –

+0

您是否已将映射更改为@GetMapping和JavaScript以使用window.location? – StanislavL

+0

是的,我按照你所说的完成了 –