前端如何下载后端传输的文件
目录
前端如何下载后端传输的文件
视频:
方式:
window.open
缺点:①无法给文件命名,②请求没有通过项目去发,而是直接打开了一个窗口,相当于是通过浏览器去请求的,没有token,无法验证请求是否合法
mounted () {
window.open("http://localhost:8000/download")
}
a标签
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” }之前
指定之后:
- 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 -> 给到对应的预览处