一、简介
前端经常会有下载文件的需求,这里总结了几种常用的方法,方便日后查看。
二、a标签下载
<a href="https://abc.png" download="abc.png" target="view_window">下载</a>
三、window.open下载
downloadTemple() { window.open(`url`); },
四、location.href
location.href = 'https://a.png';
五、saveAs
saveAs('https://abc.png')
六、loadFileSimply
6.1、loadFileSimply
// loadFileOps.js import axiosOps from 'axios'; import cookie from 'js-cookie'; import { hasIn } from 'lodash'; import Vue from 'vue'; export const $loadFileSimply = param => { let token = cookie.get('token'); let tenantId = cookie.get('tenantId'); param.url += param.url.indexOf('?') > -1 ? '&' : '?'; param.url += `tenantId=${tenantId}&_=${new Date().getTime()}`; return new Promise((resolve, reject) => { axiosOps({ url: param.url, method: param.method, data: param.data, params: param.params, responseType: 'arraybuffer', // 请求成功时,后端返回文件流,正常导出文件; headers: { Authorization: `Bearer ${token}`, tenantId: tenantId }, timeout: param.timeout ? param.timeout : 5000 }) .then(res => { resolve(res.data); }) .catch(err => { Vue.$notify.error({ title: '错误提示', message: '下载文件失败' }); reject(err) }); }); };
6.2、fileDownload
// 内容转化为文件下载 export const fileDownload = (file, fileName = '下载文件', options) => { // 创建隐藏的可下载链接 let eleLink = document.createElement('a') eleLink.download = fileName eleLink.style.display = 'none' // 字符内容转变成blob地址 let blob = options ? new Blob([file], options) : new Blob([file]) eleLink.href = URL.createObjectURL(blob) // 触发点击 document.body.appendChild(eleLink) eleLink.click() // 然后移除 document.body.removeChild(eleLink) }
6.3、使用
import { $loadFileSimply } from '@const/loadFileOps'; import { fileDownload } from '@const/utils.js'; downloadTemple() { $loadFileSimply({ url: downloadUrl, method: 'post', params: { tempCode: 'SAAS_PUR_ORDER_TEMP' }, }) .then((res) => { fileDownload(res, '文件名称.xlsx'); // 下载并修改文件名 }) .catch(() => { this.$message.error('下载模板失败!'); }); },
七、url下载
// 地址下载,fileName暂无作用 export const urlDownload = (url, fileName = '下载文件') => { // 创建隐藏的可下载链接 let eleLink = document.createElement('a') eleLink.download = fileName eleLink.style.display = 'none' eleLink.href = url // 触发点击 document.body.appendChild(eleLink) eleLink.click() // 然后移除 document.body.removeChild(eleLink) }
八、多文件下载
/** * 以iframe的方式实现的多文件下载 * @param { urls:array } - 需要下载的内容的数组列表,可以只有一条数据。 */ export const dnLoadMultipleFiles = (urls) => { if (typeof urls !== 'object' || urls.length === 0) return urls.forEach(item => { const iframe = document.createElement('iframe') iframe.style.display = 'none' // 防止影响页面 iframe.style.height = 0 // 防止影响页面 iframe.src = item document.body.appendChild(iframe) // 这一行必须,iframe挂在到dom树上才会发请求 // 5分钟之后删除(onload方法对于下载链接不起作用,就先这样吧) setTimeout(() => { iframe.remove() }, 5 * 60 * 1000) }) }
九、欢迎交流指正,关注我,一起学习。