Convert image to Base64 using Vuejs?

Asked

Viewed 3,068 times

4

I have a <input type="file /> in Vuejs and when I select an image I want it to be converted into base64, because I will save the images in the database only in base64. What would be the method to catch only the String base64 which gives rise to 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
  }
  })
}

2 answers

4


Takes the instance of new Vue by the variable vm, to gain access to imageSrc, then in the method uploadImage, utilize Filereader to load and display the image directly in the tag <img>. 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>

Reference:

2

You can do it like this...

<script>
   let image = ''
   export default{
      created(){
          this.getDataUri('urlDaImagem', (dataUri) => {
              image = dataUri
          })
      },
      methods: {
          getDataUri(url, callback){
              let image = new Image()

              image.onload = () => {
                  let canvas = document.createElement('canvas');
                  canvas.width = this.naturalWidth
                  canvas.height = this.naturalHeight
                  canvas.getContext('2d').drawImage(this, 0, 0)
                  callback(canvas.toDataUrl('image/png').replace(/^data:image\/(png|jpg);base64,/, ''))
                  callback(canvas.toDataURL('image/png'))
              }

              image.src = url
          }
      }
   }

</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.