在前端页面,html中JavaScript脚本的定义如下:

function exportFile(){        
        var form=$("<form>");
        form.attr("style","display:none");
        form.attr("target","");
        form.attr("method","post");//提交方式为post
        form.attr("action","/downloadFile");//定义action
        
        $("body").append(form);
        form.submit();        
   }

 

在Spring boot中的Controller类中创建一个方法downloadFile,方法体的定义如下:

 

 @RequestMapping("/downloadFile")

 private String downloadFile(HttpServletResponse response){
         String downloadFilePath = "/root/fileSavePath/";//被下载的文件在服务器中的路径,
         String fileName = "demo.xml";//被下载文件的名称
         
         File file = new File(downloadFilePath);
         if (file.exists()) {
             response.setContentType("application/force-download");// 设置强制下载不打开            
             response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
             byte[] buffer = new byte[1024];
             FileInputStream fis = null;
             BufferedInputStream bis = null;
             try {
                 fis = new FileInputStream(file);
                 bis = new BufferedInputStream(fis);
                 OutputStream outputStream = response.getOutputStream();
                 int i = bis.read(buffer);
                 while (i != -1) {
                     outputStream.write(buffer, 0, i);
                     i = bis.read(buffer);
                 }
               
                 return "下载成功";
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 if (bis != null) {
                     try {
                         bis.close();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 }
                 if (fis != null) {
                     try {
                         fis.close();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 }
             }
         }
        return "下载失败";    
     }

 

在前端页面点击“下载文件”按键后spring boot实现文件的下载

会自动弹出下载文件的对话框,效果图如下:

spring boot实现文件的下载

 

相关文章: