1

I am developing a file picker with Vue.js. I want to show selected file previews. I use FileReader API to achieve this. I read the user selected files as data urls with readAsDataURL method of the FileReader object.

However I get an error message saying reader.onload is not a function like:

Uncaught TypeError: reader.onload is not a function
    at VueComponent.handleFileChanges

It may be the reader is not defined, following the FileReader undefined error I have mentioned above.

How I try to do do this is as follows:

handleFileChanges (e) {
    var reader = new window.FileReader() // if window is not used it says File READER is not defined
                reader.onload(function (event) {
                  // dispatch fileAttached to state UI postEditor with event.target.result as read dataURL
                  let imageDataURL = event.target.result
                  this.$store.dispatch('attachedFile', imageDataURL) // or previewFile
                })
                reader.readAsDataURL(e.target.files[i])
}

What is the point I am missing?

0

2 Answers 2

2

Well as error says, and It's correct, It's not a function.Basically onload is event handler/property that is attached on newly constructed FileReader object and since It's not a function, It doesn't accept the any callback.

Use it like this:

handleFileChanges (e) {
    var reader = new window.FileReader() // if window is not used it says File READER is not defined
                reader.onload = function (event) {
                  // dispatch fileAttached to state UI postEditor with event.target.result as read dataURL
                  let imageDataURL = event.target.result
                  this.$store.dispatch('attachedFile', imageDataURL) // or previewFile
                }
                reader.readAsDataURL(e.target.files[i])
}

Also make sure that this at this.$store.dispatch is bounded to correct context.

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

Comments

1

Because onload is a property, you should set (modify) it as a callback. But while FileReader inherits from EventTarget, all events (onload, onabort etc.) could be used with addEventListener. So in any case that you need to pass a callback as an event handler for on-load you might consider to use addEventListener.

// method 1
reader.onload = function (e) { ...
// method 2
reader.addEventListener("onload", function (e) { ...

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.