整段 html实现其中的每一个 a 标签跨域下载操作 window.URL.createObjectURL(blob)

window.URL.createObjectURL(blob)

a 标签下载问题,通常在 a 标签中加上download属性,就可完成对href属性链接文件的下载,但仅仅是限于同源文件,如果是非同源,download 属性就会失效

第一种情况,单独的一个标签实现下载,可以使用 span 标签+click 事件模拟 a 标签的行为,

<span style="color: blue; cursor: pointer" @click="download()"></span>
function download() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "文件路径", true);
  xhr.responseType = "blob";
  xhr.onload = function () {
    const a = document.createElement("a");
    a.href = window.URL.createObjectURL(xhr.response);
    a.target = "_blank";
    a.download = "设置文件名";
    a.click();
    a.remove();
  };
  xhr.send();
}

第二种情况,是一整段 html 标签的文本,修改整段 html,实现其中的每一个 a 标签都可以完成下载操作。

创建了一个新的 Blob 对象,是一种二进制数据对象,可以用于存储和操作二进制数据。在这里使用 Blob 对象来存储一个文档的二进制数据。

第二个参数是一个对象,用于指定 Blob 对象的类型和编码方式。在这里指定了 Blob 对象的类型为 Word 文档(application/vnd.openxmlformats-officedocument.wordprocessingml.document),编码方式为 UTF-8(charset=UTF-8)。

Blob 对象可以用于下载或上传 Word 文档,或者在浏览器中预览 Word 文档。

<div v-html="content"></div>
const content = ref()
  function setAnodeAttr() {
  const html = document.getElementById('#content')
  const aList = html.getElementsByTagName('a')

  for (let i = 0; i < aList.length; i++) {
    aList[i].setAttribute('style', 'color: blue')
    const href = aList[i].getAttribute('href')
    const title = aList[i].getAttribute('title')

      await axios.get(href).then((res) => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
        })
        aList[i].setAttribute('href', window.URL.createObjectURL(blob))
        aList[i].setAttribute('download', title)
      })
  }
    // html.innerHTML  拿到最终的 文本内容使用
    content.value = html.innerHTML
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值