vue点击url下载文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue点击url下载文件

JackieDYH   2022-06-03 我要评论
  • 封装自定义指令
  • 将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标签下载即可。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们