Assigning converted `Base64` values in Javascript

2019-07-20 23:54发布

问题:

I'm trying to retrieve file information from input field of type="file" in my Vuejs application. I'm having a render function which renders the input fields something like this and calls a function on input, code as below:

input: (event) => {
    var reader = new FileReader()
    reader.readAsDataURL(event.target.files[0])
    let baseFile = ''
    reader.onload = function () {
        baseFile = reader.result
        console.log(baseFile)
    };
    console.log(baseFile)
    const docs = {
        name: event.target.files[0].name,
        size: event.target.files[0].size,
        lastModifiedDate: event.target.files[0].lastModifiedDate,
        base64: baseFile
    }
    this.$emit('input', docs)
}

When I run this function console.log inside my reader.onload function gives me converted files but when I do console outside of it, the value is just an empty string. How I can I retrieve and assign to my const docs variable. Help me out with this. Thanks.

回答1:

I recommend to put the rest of code inside the block of that function after changing it to an arrow function as follows :

input: (event) => {
  var reader = new FileReader()
  reader.readAsDataURL(event.target.files[0])
  let baseFile = ''
  reader.onload = () => {// <------ use arrow function
    baseFile = reader.result
    const docs = {
      name: event.target.files[0].name,
      size: event.target.files[0].size,
      lastModifiedDate: event.target.files[0].lastModifiedDate,
      base64: baseFile
    }
    this.$emit('input', docs)
  };


}