Vue中点击url下载文件的案例详解

Canace ·
更新时间:2024-09-20
· 1234 次阅读

目录

代码实现

使用

注意

封装自定义指令

将url转成bold,在创建a标签下载blob

代码实现

在src 下面的 directive 文件夹下新建目录 downLoadUrl

downLoadUrl / index.js文件

/* * 后端返回文件的url,前端创建a标签来下载 * * 1. 解决了若文件为图片或浏览器支持的格式类型,点击下载会直接打开文件的问题, * 2. 下载文件时,浏览器会有闪动的问题 * * 页面内使用 * 1. 引入指令 import downLoad from '@/directive/down-load-url' * 2. 注册指令 directives:{downLoad} * 3. 使用,在要下载按钮上以指令的形式使用 例如: <el-button v-downLoad="url">下载</el-button> */ import downLoad from './downLoad' const install = function(Vue) { Vue.directive('downLoadUrl', downLoad) } downLoad.install = install export default downLoad

downLoadUrl / downLoad.js文件

export default { bind(el, binding) { if (binding.value.url) { el.addEventListener('click', () => { const a = document.createElement('a') // let url = baseUrl + binding.value // 若是不完整的url则需要拼接baseURL const url = binding.value.url // 完整的url则直接使用 // 这里是将url转成blob地址, fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址 a.href = URL.createObjectURL(blob) console.log(a.href) a.download = binding.value.name || '' // 下载文件的名字 // a.download = url.split('/')[url.split('/').length -1] // // 下载文件的名字 document.body.appendChild(a) a.click() //在资源下载完成后 清除 占用的缓存资源 window.URL.revokeObjectURL(a.href); document.body.removeChild(a); }) }) } } }

在main.js注册自定义指令

使用

返回一个对象{ url: '', name: ''}

注意

1、若是文件的url存在跨域的情况,则可能会下载失败,因为fetch请求连接后,由于跨域,拿不到资源,也就无法执行后续的操作,此时是失败的。

2、也可以设置浏览器,对于一下像pdf,图片等资源不直接打开,直接下载,然后简单的创建a标签下载即可。

到此这篇关于Vue中点击url下载文件-案例的文章就介绍到这了,更多相关vue点击url下载文件内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE url

需要 登录 后方可回复, 如果你还没有账号请 注册新账号