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

2020-05-07  本文已影响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);
        });
    }

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

上一篇 下一篇

猜你喜欢

热点阅读