1, 下载后端返回的blob文件
// 下载blob文件(注意请求需要加上responseType: 'blob') export const downloadBlob = (res: Blob, fileName: string): void => { let blob = new Blob([res]) let url = window.URL.createObjectURL(blob) let downloadElement = document.createElement('a') downloadElement.style.display = 'none' downloadElement.download = fileName downloadElement.href = url document.body.appendChild(downloadElement) downloadElement.click() document.body.removeChild(downloadElement) }
2, 浏览器下载 txt,jpg等文件而不是自动打开预览
// 下载链接内容(解决浏览器下载 txt,jpg等文件自动打开预览页面的问题) export const downloadLink = (fileUrl: string, fileName: string): void => { fetch(fileUrl) .then((res) => res.blob()) .then((blob) => { // 将链接地址字符内容转变成blob地址 const link = document.createElement('a') link.href = URL.createObjectURL(blob) link.download = fileName link.target = '_blank' document.body.appendChild(link) link.click() link.remove() }) .catch(() => { alert('下载文件失败') }) }
标签:文件,res,前端,link,blob,downloadElement,document,下载 From: https://www.cnblogs.com/cuijinlin/p/16825605.html