在 Vue.js 组件方法中使用 FileReader API

Using FileReader API inside a Vue.js component method

我正在使用 Vue.js 开发一个文件选择器。我想显示选定的文件预览。 我使用 FileReader API 来实现这一点。我使用 FileReader 对象的 readAsDataURL 方法将用户选择的文件读取为数据 url。

但是我收到一条错误消息,说 reader.onload 不是像这样的函数:

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

可能是 reader 未定义,出现我上面提到的 FileReader 未定义错误。

我尝试这样做的方法如下:

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

我漏掉了什么?

正如错误所说,它是正确的,它不是 function.Basically onload 是事件 handler/property 附加在新建的 FileReader 对象上,因为它不是一个函数,它不接受任何回调。

这样使用:

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

还要确保 this.$store.dispatch 处的 this 绑定到正确的上下文。

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