【下载】前端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();
	}
}

猜你喜欢

转载自blog.csdn.net/NineWaited/article/details/128558922