Convert file to base64 on fron-end in VueJS

It's a normal task to upload a file from the front-end to the back-end. And every developer tried it. Posting a file with a form data type request is a normal way. But what if we want to show a image before upload it to the server? We have an image box and we want to show it to the user before save it.

I found a solution base on base64. I convert the image to base64 and assign it to a variable and connect the image box to present it. Also we can upload base64 to the server and there we convert it to binary image format and save it!

In VueJS, I using the watch to monitor changes on the image field that a user use to select a image, and after user choose a image, front-end app convert it to a base64 string and store it into another variable that connected to the image box.

Let check them in code. At first, I'll define two variable:

  1. image: connected to file input
  2. base64: to keep result of conversion
Then I set a watcher on image, to update base64 variable on image's changes:


    image: function (newVal, oldVal) {
      if(newVal) {
        this.createBase64Image(newVal);
      } else {
        this.base64 = null;
      }
    }

And at the end, I define a function to convert image to base64 and update base64 variable:


    createBase64Image: function(FileObject) {
      const reader = new FileReader();
      reader.onload = (event) => {
        this.base64 = event.target.result;
      }
      reader.readAsDataURL(FileObject);
    }

You can check out https://codepen.io/glinboy/pen/KKvEzjy for an online sample :)

No comments: