前端实现下载文件
一、通过url-loader插件
对于保存在项目中的文件,实现直接下载该文件至本地。
对这个插件的具体理解可以查看别的网上介绍:
- https://zhuanlan.zhihu.com/p/85917267
- https://blog.csdn.net/qq_46112274/article/details/122940667
这里直接上代码
- 修改vue.config.js配置
// 我的项目是webpack + vue,所以在vue.config.js文件中修改配置
configureWebpack: {
module: {
rules: [{
test: /\.xlsx$/,
use: [{
loader: "url-loader",
options: {
name: 'files/[name].[ext]'// 命名生成的文件名称
}
}]
}]
},
}
- 代码中使用下载功能或者说直接引入文件
场景1
import myFile from "@/assets/doc/test.xlsx"; // 直接引入文件对象,可以用在引入图片的场景
场景2
<a :href="require('@/assets/doc/test.xlsx')" download="模板文件">下载文件</a>
二、通过完整url链接下载文件
通过模拟接口请求实现,这样就支持在请求头部加入自定义配置了(有些场景需要通过鉴权后才允许下载,要带上鉴权的信息)。
// 定义下载的方法
function downloadFile(url, fileName) {
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Authorization', "token信息")
xhr.responseType = 'blob';
// 注册事件监听函数
xhr.onload = () => {
if (xhr.status === 200) {
// 成功获取文件
var blob = xhr.response;
// 创建a标签,用于下载该文件
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// 释放资源
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
} else {
// 获取文件失败
console.log('Failed to download file');
}
};
// 发送请求
xhr.send();
}
// 调用方法执行
const url = "http://xxxxxxx";
const fileName = "这是下载的文件名称";
downloadFile(url, fileName);