Assigning converted `Base64` values in Javascript

2019-07-20 23:37发布

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条回答
劫难
2楼-- · 2019-07-21 00:05

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)
  };


}
查看更多
登录 后发表回答