2020/04/08

Vue.js Upload file using axios

<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
  }

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)
    }
  })
}