Image Upload
It's just a couple of steps to upload any file (including images) via Vue.js. Here they are!
Vue.js Image Upload
Uploading images basically is a two-step process:
Select a File
Before we can upload it, we have to select a file.
To allow the user to pick a file, we have to add <input type="file">
to our component template code. We also have to listen to any changes to that file. Such a change handler will trigger whenever the user picks a new file.
Like this:
<input type="file" @change="onFileChanged"><button @click="onUpload">Upload!</button>
We now need the two handler methods in our Vue component:
methods: {onFileChanged (event) {const file = event.target.files[0]},onUpload() {// upload file}
To upload the file, we should store it in our data property:
data() {return {selectedFile: null}},methods: {onFileChanged (event) {this.selectedFile = event.target.files[0]},onUpload() {// upload file, get it from this.selectedFile}
Send the File to a Server
With the file stored in state, we can send it to a server.
For this, you can use axios. You can either send the file as binary data or wrapped in a FormData
object - depending on what your REST API expects.
Send as binary data
onUpload() {axios.post('my-domain.com/file-upload', this.selectedFile)}
Send as FormData
onUpload() {const formData = new FormData()formData.append('myFile', this.selectedFile, this.selectedFile.name)axios.post('my-domain.com/file-upload', formData)}
Show upload progress
In both cases, you can also output the upload progress if you want to.
uploadHandler = () => {...axios.post('my-domain.com/file-upload', formData, {onUploadProgress: progressEvent => {console.log(progressEvent.loaded / progressEvent.total)}})}