2

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 guess you should assign var inside callback of reader.onload Commented Dec 27, 2018 at 12:59

1 Answer 1

3

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


}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.