vue如何根据url下载非同源文件

一般情况下,我们根据url下载文件时可以有以下两种方案:

1. window.open(url)

2. <a :href="https://juejin.cn/post/url" download="文件名称"/>

但是我们在开发过程中,有时会遇到后端返回的文件地址和我们的网站不是同源的情况下,使用以上两种方案下载图片、pdf等文件,浏览器会直接打开,而不是下载。下面这种方法就可以解决此类情况:

下载文件函数封装:(views/util/index.js)

import axios from "axios";
// 下载文件(可解决跨域下载问题)
export async function downloadFile(fileUrl, fileName) {
  if (!fileUrl) return;
  let res = await axios({
    method: "get",
    url: fileUrl,
    responseType: "blob"
  });
  let newUrl = window.URL.createObjectURL(res.data);
  let a = document.createElement("a");
  a.href = newUrl;
  a.download = fileName;
  a.click();
  a.remove();
  //在资源下载完成后 可以人工清除createObjectURL 占用的缓存资源
  window.URL.revokeObjectURL(newUrl);
}

复制代码

使用

<template>
  <div>
      {{file.name}}
      <span
        class="file-download"
        @click="downloadFile(file.url, file.name)"
        >下载</span
      >
  </div>
</template>

<script>
import { downloadFile } from "@/util/index.js";
export default {
  components: {},
  data() {
    return {
      file:{
          url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb.zol-img.com.cn%2Fdesk%2Fbizhi%2Fimage%2F6%2F960x600%2F1426818724752.jpg&refer=http%3A%2F%2Fb.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627377638&t=662034e86ff9110854ca0316485e294b',
          name:'美景图'
      }
    };
  },
  created() {},
  mounted() {},
  methods: {
    downloadFile
  }
};
</script>

<style lang="scss" scoped>

</style>

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享