Convert image to base64 using VueJS?

3

I have <input type="file /> in VueJS and when I select an image I want it to be converted to base64 , because I will save the images in the database only in base64 . What would be the method to get only the String base64 that 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
  }
  })
}
    
asked by anonymous 03.10.2017 / 15:51

2 answers

3

Get the instance of new Vue for the variable vm , to get access to imageSrc , then on the uploadImage method, use FileReader to load and display the direct image in 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><divid="editor">
  <p>
   <input @change="uploadImage" type="file" name="photo" accept="image/*">
  </p>
  <img :src="imageSrc" class="image">  
</div>

03.10.2017 / 16:46
2

You can do this 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>
    
03.10.2017 / 16:44