Vue下载本地pdf、word、excel文件

Vue下载本地pdf、word、excel文件

项目需求

在项目中需要对pdf、word、excel等文档的下载
也就是获取文件的静态路径,下载到本地。
方案 :利用 axios 下载

具体实现

项目技术 Vue2 + element UI中实现
首先需要一个按钮来触发点击事件

<el-button type="primary" @click="download">下载文档</el-button>

在需要下载文档的页面引入 axios

import axios from 'axios';

将需要导出的文件放到 static 文件下

download(){
	axios('static/file.pdf',{
		responseType: 'blob', //重要代码
	}).then(res =>{
		const url = window.URL.createObjectURL(new Blob([res.data]));
		const link = document.createElement('a');
        link.href = url;
        let fileName = "使用说明文档" //保存到本地的文件名称
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
	}
}

项目技术 Vue3 + element UI中实现
与Vue2项目一样,需要按钮来触发事件

<el-button type="primary" @click="download">下载文档</el-button>

在需要下载文档的页面引入 axios

import axios from 'axios';

将需要导出的文件放到 public 文件下
实现下载代码一致

download(){
	axios('static/file.pdf',{
		responseType: 'blob', //重要代码
	}).then(res =>{
		const url = window.URL.createObjectURL(new Blob([res.data]));
		const link = document.createElement('a');
        link.href = url;
        let fileName = "使用说明文档" //保存到本地的文件名称
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
	}
}

注意

Vue2中的静态资源在 static
Vue3中的静态资源则在 public
文件存放错的话,会获取不到本地文件的。

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值