美文网首页
SpringBoot 文件下载(前端+后端)

SpringBoot 文件下载(前端+后端)

作者: 邮差在行动 | 来源:发表于2020-05-07 13:29 被阅读0次

SpringBoot 下载static目录下的静态文件

  • 后端
@PostMapping("/download/file")
public void downloadTemplate(HttpServletResponse response, 
           @RequestParam("name") String fileName) throws IOException {
       String path = "/static/files/"+fileName;
       downloadFile(response, path, fileName);
}

private void downloadFile(HttpServletResponse response, String path, String fileName) throws IOException {
       /** 将文件名称进行编码 */
       response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
       response.setContentType("content-type:octet-stream");
       /** 读取服务器端模板文件 */
       InputStream inputStream = this.getClass().getResourceAsStream(path);

       /** 将流中内容写出去 */
       OutputStream outputStream = response.getOutputStream();
       byte[] buffer = new byte[1024];
       int len;
       while ((len = inputStream.read(buffer)) != -1) {
           outputStream.write(buffer, 0, len);
       }
       inputStream.close();
       outputStream.close();
   }
  • 前端
var downloadFile = function (fileName){
        let url = "/download/file";
        var params = new URLSearchParams();
        params.append("name", fileName);
        axios.post(url, params,
            {responseType: 'blob'}  //这个不能少,让response二进制形式,如果你按照网上教程不设置这个将返回值进行BLOB([])进行处理可能会出现解析错误
        ).then(response => {
            const href = URL.createObjectURL(response.data);
            const a = document.createElement('a');
            a.setAttribute('href', href);
            a.setAttribute('download', fileName);
            a.click();
            URL.revokeObjectURL(href);
        });
    }

代码源于网络,整理一下,有问题可留言。

相关文章

网友评论

      本文标题:SpringBoot 文件下载(前端+后端)

      本文链接:https://www.haomeiwen.com/subject/vdmaihtx.html