我试图在我的个人网站上创建一个下载按钮,供人们下载我的 docx 简历,但遇到了一些问题。
首先我用简单的 href 链接来做到这一点
<a href="xxx.docx" download><button>download my resume</button></a>
但没有用。
然后我尝试了 axios 方式,创建一个按钮,并将单击操作绑定到下载 File(){} 方法,但不起作用,出现错误
GET http://localhost:8080/assets/assets/imgs/cv_eudora.docx
404(未找到)
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)
![screenshot](https://i.stack.imgur.com/Ix3AL.png)
我认为这是因为 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>
or
-
使用显式导入您的文件require()功能
<a :href="require('../assets/imgs/cv_eudora.docx')" download="cv_eudora.docx">
download my resume
</a>
然而,要使其工作,您需要配置 Webpack 来加载.docx
文件通过file-loader
. In 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]' })
}
}
See https://cli.vuejs.org/guide/webpack.html#adding-a-new-loader
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)