vue.jsHow do I upload a file using Vue.js?
Using Vue.js, you can upload files by using v-on
to listen for a file input event, then using FormData
to package the file data.
Example code
<input type="file" v-on:change="onFileChange">
...
methods: {
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
}
}
Then, to actually upload the file, you can use FormData
to package the file data and send it to your server.
Example code
let formData = new FormData();
formData.append('file', file);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
The code above will send a POST request to /upload
with the file data included in the request body. The response will be logged to the console.
Parts of the code:
<input type="file" v-on:change="onFileChange">
- listens for a file input eventonFileChange(e)
- handles the file input eventcreateImage(files[0])
- creates an image from the filelet formData = new FormData()
- creates a new FormData objectformData.append('file', file)
- adds the file data to the FormData objectaxios.post('/upload', formData, {...})
- sends a POST request with the FormData object in the request bodyconsole.log(response)
- logs the response to the console
Helpful links
More of Vue.js
- How can I implement pinch zoom functionality in a Vue.js project?
- How do I determine which version of Vue.js I am using?
- How do I use the v-if directive in Vue.js?
- How do I use Yup with Vue.js?
- How can I use Vue and Chart.js to add zoom functionality to my chart?
- How to use a YAML editor with Vue.js?
- How can I convert XML data to JSON using Vue.js?
- How can I use Vue.js to create a XSS payload?
- How do I use the Vue.js Wiki?
- How do I use the v-model in Vue.js?
See more codes...