如何创建文件下载按钮?<人力资源和Axios不起作用

人气:895 发布:2022-10-16 标签: download docx vue.js webpack

问题描述

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

首先我是用简单的href链接做的

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

但没有起作用。

然后我尝试了AXOIS方法,使用绑定到DownloadFile(){}方法的单击操作创建了一个按钮,但不起作用,并出现错误

获取http://localhost:8080/assets/assets/imgs/cv_eudora.docx404(未找到)

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,因此默认情况下它们不会包含在您的内部版本中。

您在此有两个选项...

将您的文件放入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>

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

868