如何创建文件下载按钮? <a href> 和 Axios 不工作

How to create a file download button? <a href> and Axios not working

我正尝试在我的个人网站上创建一个下载按钮,供人们下载我的 docx 简历,但遇到了一些问题。

首先我用简单的 href link 之类的东西

<a href="xxx.docx" download><button>download my resume</button></a>

但没有用。

然后我尝试了 axois 方式,创建了一个带有点击操作的按钮绑定到 downloadFile(){} 方法,没有用,出现了错误

GET http://localhost:8080/assets/assets/imgs/cv_eudora.docx 404 (Not Found)

Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:59)

我想是因为downloadFile(){}函数中的url部分没写好,不知道vue中路径的正确写法。路径本身应该是正确的,因为当我这样做时,它甚至一直都有自动提示选项。

<button @click="downloadFile()">download my resume</button>
downloadFile() {
      axios({
        url: "../assets/imgs/cv_eudora.docx",
        method: "GET",
        responseType: "blob" // important
      }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "eudoraCV.docx"); //or any other extension
        document.body.appendChild(link);
        link.click();
      });
    }

这里的问题是 Webpack 加载程序不适用于 <a href> URL,因此默认情况下它们不会包含在您的构建中。

这里有两个选择...

  1. 将您的文件放入 the public folder 并像这样引用它

    export default {
      // add the base URL to your component's "data" function
      data: () => ({ publicPath: process.env.BASE_URL })
    }
    
    <a :href="`${publicPath}cv_eudora.docx`" download>
      download my resume
    </a>
    

  2. 使用 require() 函数显式导入您的文件

    <a :href="require('../assets/imgs/cv_eudora.docx')" download="cv_eudora.docx">
      download my resume
    </a>
    

    然而,要使其正常工作,您需要配置 Webpack 以通过 file-loader 加载 .docx 文件。在vue.config.js中,你可以告诉Webpack通过添加一个新的模块规则来打包文档...

    module.exports = {
      chainWebpack: config => {
        config.module.rule('downloads')
          // bundle common document files
          .test(/\.(pdf|docx?|xlsx?|csv|pptx?)(\?.*)?$/)
          .use('file-loader')
            // use the file-loader
            .loader('file-loader')
            // bundle into the "downloads" directory
            .options({ name: 'downloads/[name].[hash:8].[ext]' })
      }
    }
    

    https://cli.vuejs.org/guide/webpack.html#adding-a-new-loader