<template>
  <div>
    <button @click='downloadFile'>Download File</button>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  name: 'DownloadFile',
  data() {
    return {
      filePath: '/path/to/file.pdf', // 文件路径
      fileName: 'file.pdf', // 文件名
    };
  },
  methods: {
    async downloadFile() {
      try {
        const response = await axios.get(this.filePath, {
          responseType: 'blob', // 指定响应类型为 blob
        });
        const url = window.URL.createObjectURL(new Blob([response.data])); // 创建一个临时 URL
        const link = document.createElement('a'); // 创建一个下载链接
        link.href = url;
        link.setAttribute('download', this.fileName); // 设置下载文件名
        document.body.appendChild(link);
        link.click(); // 模拟点击下载链接
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>
<p>该组件通过 axios 发送请求获取文件内容,并将响应类型指定为 blob。然后,通过 <code>window.URL.createObjectURL()</code> 创建一个临时的 URL,将其赋值给下载链接的 href 属性。最后,通过 <code>link.click()</code> 模拟点击下载链接,即可触发浏览器的下载行为。</p>
Vue3.0 文件下载:最佳实践和代码示例

原文地址: https://www.cveoy.top/t/topic/nLFm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录