javascript – Convert image to base64 using VueJS?

Question:

I have an <input type="file /> in VueJS and when I select an image I want it converted to base64 as I will save the images in the database only in base64 . What would be the method to get only the base64 String that gives rise the image?

<input @change="uploadImage" type="file" name="photo" accept="image/*">
<img :src="imageSrc" class="image">

uploadImage: function (e) {
  var files = e.target.files
  if (!files[0]) {
    return
  }
  var data = new FormData()
  data.append('media', files[0])
  var reader = new FileReader()
  reader.onload = (e) => {
    this.imageSrc = e.target.result
  }
  })
}

Answer:

Get the new Vue instance by the vm variable, to access the imageSrc , then in the uploadImage method, use FileReader to load and display the image directly in the <img> tag. Example:

Vue.config.debug = false;
Vue.config.devtools = false;
Vue.config.silent = true;

var vm = new Vue({
  el: '#editor',
  data: {
    imageSrc: null
  },
  methods: {
    uploadImage: function() {    
      var file = document
        .querySelector('input[type=file]')
        .files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        vm.imageSrc = e.target.result             
      };
      reader.onerror = function(error) {
        alert(error);
      };
      reader.readAsDataURL(file);      
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="editor">
  <p>
   <input @change="uploadImage" type="file" name="photo" accept="image/*">
  </p>
  <img :src="imageSrc" class="image">  
</div>

Referencia:

Scroll to Top