目录

前端如何下载后端传输的文件

目录

前端如何下载后端传输的文件

视频:

方式:

https://i-blog.csdnimg.cn/direct/79b7bbc0448e4e98a6d3eae40458040e.png

  1. window.open

    缺点:①无法给文件命名,②请求没有通过项目去发,而是直接打开了一个窗口,相当于是通过浏览器去请求的,没有token,无法验证请求是否合法

mounted () {
	window.open("http://localhost:8000/download")
}
  1. a标签

    https://i-blog.csdnimg.cn/direct/fcf31ed68d2047c38dbc9be777a188c0.png

    https://i-blog.csdnimg.cn/direct/f9b1a17c385a4c77b313fdf9dd2de4d5.png

mounted () {
	//1,按blob请求接口(用 blob 接收后端传过来的二进制文件,将二进制字符串转为文件流)
	axios.get("http://localhost:8000/download", { responseTypе: "blob" }).then((res) => {
		console.log(res.data);
		if (window.navigator.msSaveBlob) {
			// IE -兼容IE 第三个参数为文件名
			window.navigator.msSaveBlob(res.data,
			{ type: "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
			"test.ppt"
			)
		} else {
			//2,创建blob的本地url
			let blobURL = URL.createobjectURL(res.data);
			console.log(blobURL);
			//3,创建标签
			let link = document.createElement("а");
			//4,设置href
			link.href = blobURL
			//5,设置download(告诉a标签其行为是下载)
			link.download = "test2.ppt"
			link.style.display = "none";
			link.click();
			URL.revokeObjectURL(blobURL);
		}
	}
}

console.log(res.data); 的结果:

没有指定 { responseTypе: “blob” }之前

https://i-blog.csdnimg.cn/direct/9ce090e6c2be4598816b3622a848d1df.png

指定之后:

https://i-blog.csdnimg.cn/direct/a586128e2a4b46989c1d4b6a1f8ea69b.png

  1. file-saver
import { saveAs } from "file-saver"

mounted () {
	//1,按blob请求接口(用 blob 接收后端传过来的二进制文件,将二进制字符串转为文件流)
	axios.get("http://localhost:8000/download", { responseTypе: "blob" }).then((res) => {
		saveAs(res.data, "fileSaveDownload.ppt"):
	}
}

预览:

图片,excel , word -> 给一个地址url就行了

url -> 线上地址 or base64URL

base64URL:

接收文件的blob -> 通过fileReader -> 转成base64URL -> 给到对应的预览处