vue axios 下载文件

参考 https://www.jianshu.com/p/2d92e169fa65
后台

response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8") + ".xls");

前台

axios({
         method: 'post',
         url: url,
         // headers里面设置token
         data:params,
          // 二进制流文件,一定要设置成blob,默认是json
         responseType: 'blob'
         }).then(res => {
           // 获取到请求头中的name
            let contentDisposition = res.headers['content-disposition'];  //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
           let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
           let result = patt.exec(contentDisposition);
           let filename = decodeURI(result[1]);
            // 开始下载
           const link = document.createElement('a')
           const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
           link.style.display = 'none'
           link.href = URL.createObjectURL(blob)
            link.setAttribute('download', filename)
           document.body.appendChild(link)
           link.click()
           document.body.removeChild(link)
     })
后端请求头数据.png

你可能感兴趣的:(vue axios 下载文件)