How to upload a file in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to process and upload a file in Vue.js using form input field.

Let’s create a form field that will accept image files and make a POST request to the backend server.

HTML

<button class="btn btn-info" @click="onPickFile">Upload profile picture</button>
<input
  type="file"
  style="display: none"
  ref="fileInput"
  accept="image/*"
  @change="onFilePicked"/>

We’ve masked our input field to make upload button customisable. File input fields usually use default browser styling and not easily customisable.

As you can see there should be two methods called onPickFile() and onFilePicked(), let’s build them.

Vue.js

onPickFile () {
  this.$refs.fileInput.click()
},
onFilePicked (event) {
  const files = event.target.files
  let filename = files[0].name
  const fileReader = new FileReader()
  fileReader.addEventListener('load', () => {
    this.imageUrl = fileReader.result
  })
  fileReader.readAsDataURL(files[0])
  this.image = files[0]
}

Now when you click on the “Upload profile picture” button it will call the onFilePicked() method, which will programmatically trigger the file input field.

When you select a file to upload, onFilePicked() method will be called. This is where you can validate whether maximum file size was exceeded, file format etc.

If it passes validation the file will be assigned to the image filed in the data() object.

export default {
  data () {
    return {
      image: null
    }
  }
}

You can then write a method that will submit your file to the back-end server, e.g. firebase.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-file-upload

PS: Make sure you check other JavaScript tutorials, e.g. useful Vue.js filtershow to stop mouse event propagation in Vue.js and load external CSS file into Vue.js component.

Write a Comment

Comment