sçuçu
sçuçu

Reputation: 3070

Using FileReader API inside a Vue.js component method

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?

Upvotes: 1

Views: 5892

Answers (2)

Kerem
Kerem

Reputation: 11566

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) { ...

Upvotes: 1

Belmin Bedak
Belmin Bedak

Reputation: 9201

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.

Upvotes: 2

Related Questions