【下载】前端JS下载文件的三种方法。FileSaver解决了PDF下载会先预览的问题。

普通a标签下载

这是非异步下载,后端注意不要写@ResponseBody
在获取pdf文件流的时候会默认使用浏览器打开。a标签无法解决。

const a = document.createElement('a');
var href= "/template/"+format+"/"+this.templateInfoForm.templateName;
a.setAttribute('href', href);
// 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
var filename = this.templateInfoForm.templateName + "." + format
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// 在内存中移除URL 对象
window.URL.revokeObjectURL(herf);

搭配FileSaver的axios异步下载

亲测可以解决pdf下载文件流会先预览的问题。

  • 需要先安装组件:npm install file-saver --save
  • 在当前vue中import组件:import FileSave from 'file-saver'
  • 使用saveAs()方法保存blob文件流,避免预览
var filename = this.templateInfoForm.templateName + "." + format
var url = "/template/"+format+"/"+this.templateInfoForm.templateName;
//异步申请文件流
this.$http.get(
    url, 
    {
        headers:{
            "Content-Type" : "application/octet-stream", 
        },
        responseType: "blob"
    }
).then((res) => {
    var file = new Blob([res.data], { 
        type: 'application/'+format 
    });
    //直接下载而不预览
    saveAs(file, filename);
});

搭配FileSaver的原生异步下载

亲测可以解决pdf下载文件流会先预览的问题。

  • 需要先安装组件:npm install file-saver --save
  • 在当前vue中import组件:import FileSave from 'file-saver'
  • 使用saveAs()方法保存blob文件流,避免预览
//访问后端的文件链接
var url = "/template/"+format+"/"+this.templateInfoForm.templateName;
//你要保存的文件名
var filename = this.templateInfoForm.templateName + "." + format
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
//配置请求头
oReq.responseType = "blob";
//对响应对象进行配置
oReq.onload = function() {
    //对响应头进行配置
    var file = new Blob([oReq.response], { 
        type: 'application/'+format
    });
    //把文件流直接保存到本地,可以避免用浏览器打开(比如pdf)
    saveAs(file, filename);
};
oReq.send();

后端写入文件流参考

//下载模板的pdf版本
@GetMapping("/template/pdf/{templateName}")
@ResponseBody
public void getPdf(@PathVariable("templateName") String templateName, HttpServletResponse response) {
	String filePath = templateLocation.getLocation() + templateName + "\\" + templateName + ".pdf";
	
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	try {
	    bis = new BufferedInputStream(new FileInputStream(filePath));
	    bos = new BufferedOutputStream(response.getOutputStream());
	    byte[] buffer = new byte[1024];
	    int length;
	    while ((length = bis.read(buffer)) != -1) {
	        bos.write(buffer, 0, length);
	    }
	    bis.close();
	    bos.close();
	}catch (Exception e) {
	    e.printStackTrace();
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玖等了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值