美文网首页
vue 通过url 点击下载 图片或PDF

vue 通过url 点击下载 图片或PDF

作者: IssunRadiance | 来源:发表于2024-07-30 15:08 被阅读0次

如果链接是一个 表格 或者 压缩包等,如:
https://test-pic.tsingglobal.com/purchasePrice1722394574227.xlsx
这时使用 window.open(url), 可以直接打开新窗口,将文件下载致本地

但是当链接为 PDF 或者 图片的时候,使用window.open(), 就会变成预览效果,不会自动下载。

这时如果我们想点击 直接下载
使用以下方法:

<el-link type="primary" @click="downloadImg('https://test-pic.tsingglobal.com/PN2MVj1wgbeA7m1r', '下载的图片名称')">下载</el-link>
downloadImg(url, fileName) {
  const x = new window.XMLHttpRequest();
  x.open('GET', url, true);
  x.responseType = 'blob';
  x.onload = () => {
    const url = window.URL.createObjectURL(x.response);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.click();
  };
  x.send();
},

相关文章

网友评论

      本文标题:vue 通过url 点击下载 图片或PDF

      本文链接:https://www.haomeiwen.com/subject/vkjghjtx.html