Vue中点击url下载文件-案例

  • 封装自定义指令
  • 将url转成bold,在创建a标签下载blob

代码实现

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

《Vue中点击url下载文件-案例》

  1. 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
  1. 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);
                })
            })
        }
    }
}
  1. 在main.js注册自定义指令

《Vue中点击url下载文件-案例》

使用

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

《Vue中点击url下载文件-案例》

 《Vue中点击url下载文件-案例》

注意

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

《Vue中点击url下载文件-案例》

2、也可以设置浏览器,对于一下像pdf,图片等资源不直接打开,直接下载,然后简单的创建a标签下载即可。《Vue中点击url下载文件-案例》

    原文作者:普通网友
    原文地址: https://blog.csdn.net/JackieDYH/article/details/124051194
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞