以下是一个基本的文件下载的 Vue3.0 组件:

<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>

其中,通过 axios 发送请求获取文件内容,并将响应类型指定为 blob。然后,通过 window.URL.createObjectURL() 创建一个临时的 URL,将其赋值给下载链接的 href 属性。最后,通过 link.click() 模拟点击下载链接,即可触发浏览器的下载行为

vue30 后台给文件路径 前端怎么写好下载 才是最优 请提供下代码

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

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