0


Vue根据网络文件路径下载文件【自定义属性 v-down】

Vue根据网络文件路径下载文件【v-down】

提到下载文件大家首先肯定会想到 模拟点击 、a标签等
因为发现公司同事还在使用向后端拿二进制流来下载,这就对后端的流操作以及前端的工作增加了不少工作量,偶然想到使用VUE自定义属性来快速实现下载文件、图片等

  1. 我们会发现在使用a标签等操作下载图片时会被浏览器识别直接打开预览,效果十分不佳,废话不说上代码,下载文件so easy

标准使用方式

  1. <script>
  2. Vue.directive('down',{inserted:(el, binding)=>{
  3. el.style.cssText ='cursor: pointer;color:write;'
  4. el.addEventListener('click',()=>{
  5. console.log(binding.value)let link = document.createElement('a')let url = baseDownloadUrl + binding.value
  6. // 这里是将url转成blob地址,fetch(url).then(res=> res.blob()).then(blob=>{// 将链接地址字符内容转变成blob地址
  7. link.href =URL.createObjectURL(blob)
  8. console.log(link.href)
  9. link.download =''
  10. document.body.appendChild(link)
  11. link.click()})})}})</script>//使用方式<span v-down="url">下载</span>
  1. 以上为常规标准使用方法,但在企业级开发中,我们都是使用全局挂载的方式来完成的

企业级Vue开发集成(全局挂载)

  1. 此处以若依框架为例:

1.src目录下创建directive文件夹(存在则忽略)

在这里插入图片描述

  • directive目录下创建download目录
  • 创建down.js文件

2.down.js文件

  1. /**
  2. * 下载文件
  3. */exportdefault{inserted:(el, binding)=>{
  4. el.style.cssText ='cursor: pointer;color:write;'
  5. el.addEventListener('click',()=>{
  6. console.log(binding.value)let link = document.createElement('a')let url = binding.value
  7. // 这里是将url转成blob地址,fetch(url).then(res=> res.blob()).then(blob=>{// 将链接地址字符内容转变成blob地址
  8. link.href =URL.createObjectURL(blob)
  9. console.log(link.href)
  10. link.download =''//为空使用下载名称
  11. document.body.appendChild(link)
  12. link.click()})})}}

3.directive根目录创建index.js文件

  1. 文件内容如下
  1. import down from'./download/down'constinstall=function(Vue){
  2. Vue.directive('down', down)}exportdefault install

4.main.js 注册自定义属性全局挂载

  1. import directive from'./directive'// directive
  2. Vue.use(directive)
  1. 各个组件中使用
  1. //任何标签均可使用 且不用担心跨域<span v-down="durl" style="width:100px;height:50px">下载</span>
  1. 代码本人亲测有效,不喜勿喷,谢谢

本文转载自: https://blog.csdn.net/weixin_42081445/article/details/128721904
版权归原作者 一名技术极客 所有, 如有侵权,请联系我们删除。

“Vue根据网络文件路径下载文件【自定义属性 v-down】”的评论:

还没有评论