Sometimes, we want to upload image in Vue.js.
In this article, we’ll look at how to upload image in Vue.js.
How to upload image in Vue.js?
To upload image in Vue.js, we can add a file input, watch for file selection, and upload the file when a file is selected.
For instance, we write
<template>
<input type="file" accept="image/*" @change="uploadImage" />
</template>
<script>
//...
export default {
//...
methods: {
async uploadImage(event) {
const URL = "http://foobar.com/upload";
const data = new FormData();
data.append("name", "my-picture");
data.append("file", event.target.files[0]);
const config = {
header: {
"Content-Type": "image/png",
},
};
await axios.put(URL, data, config);
},
},
//...
};
</script>
to set the change
event handler to the uploadImage
method on the file input.
In uploadImage
, we put the image in the form data body with
data.append("file", event.target.files[0]);
And then we call axios.put
to make a PUT request with the URL
, form data data
and the config
for the request.
Conclusion
To upload image in Vue.js, we can add a file input, watch for file selection, and upload the file when a file is selected.