Reputation: 177
I'm trying to create a download button on my personal website for people to download my docx resume, but had some issues.
first i did it with simple href link thingy like
<a href="xxx.docx" download><button>download my resume</button></a>
but didn't work.
then i tried axois way, creating a button with the click action bind to the downloadFile(){} method, didn't work, coming with the error
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)
I think it's because the url part in the downloadFile(){} function that's not stated properly, but don't know the right way to write the path in vue. The path itself should be right because it even had the automatic hint options all the way when i did it.
<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();
});
}
Upvotes: 3
Views: 5969
Reputation: 164914
The issue here is that the Webpack loaders do not apply to <a href>
URLs so they won't be included in your build by default.
You have two options here...
Put your file in the public
folder and reference it like this
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
Explicitly import your file using the require()
function
<a :href="require('../assets/imgs/cv_eudora.docx')" download="cv_eudora.docx">
download my resume
</a>
For this to work however, you need to configure Webpack to load .docx
files via the file-loader
. In vue.config.js
, you can tell Webpack to bundle documents by adding a new module rule...
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
Upvotes: 5