1.若后端直接返回链接地址,可以直接进行预览或者下载,配置响应头,如下:
Content-Disposition
:这个响应头可以决定内容是 预览 还是 下载。
它支持三种格式的值:
Content-Disposition: inline
此时,消息体会以页面的一部分或者整个页面的形式展示。(预览)Content-Disposition: attachment
消息体应该被下载,默认文件名和url
格式有关。Content-Disposition: attachment; filename="filename.jpg"
消息体应该被下载,默认文件名可指定。
注:如果需要预览,需要配合适当的
Content-Type
食用;
实例:
const user = {
name: "嘻嘻嘻",
blogUrl: "https://juejin.cn/user/1714893870865303"
}
const contentDispositionInline = async (req, res, next) => {
res.setHeader('Content-Disposition', 'inline')
res.send(user)
}
const contentDispositionFilename = async (req, res, next) => {
res.setHeader('Content-Disposition', 'attachment; filename="chunge.json"')
res.send(user)
}
const contentDispositionNoFilename = async (req, res, next) => {
res.setHeader('Content-Disposition', 'attachment')
res.send(user)
}
参考链接:用头👴解决!前端必知必会的几个实用响应头 - 掘金
2.base64转化为blob 后进行下载(需要后端的配合)
// 附件下载 这里的的data就是content数据
const downloadAttach = (id) => {
downloadAttachment({ attachmentId: id })
.then(({ data }) => {
const raw = window.atob(data.content);//解码base64
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i); //转换为 Uint8
}
const blob = new Blob([uInt8Array], { type: data.contentType });
// 下载方法
const elink = document.createElement("a");
elink.download = data.attachName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
// 预览方法
window.open(URL.createObjectURL(blob))
})
.catch(() => {});
};
3.利用插件file-svaer
/**
* @description 文件下载
* @param { string } path 地址
* @param { string } name 名称
*/
import FileSaver from "file-saver"
fileSave(path, name) {
FileSaver.saveAs(path, name)
},
//若返回的是blob流
let blob = new Blob([path], { type })
fileSave(blob,name)