在Vue.js组件中使用FileReader API方法
问题描述:
我正在用Vue.js开发一个文件选取器。我想显示选定的文件预览。 我使用FileReaderAPI来实现这一点。我使用FileReader
对象的readAsDataURL
方法将用户选择的文件作为数据url进行读取。在Vue.js组件中使用FileReader API方法
但是我得到一个错误信息说reader.onload
是不是像一个函数:
Uncaught TypeError: reader.onload is not a function
at VueComponent.handleFileChanges
这可能是读者没有定义,下面我上面提到的的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
是连接新建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
在this.$store.dispatch
为界,正确的上下文。
答
因为onload是一个属性,所以您应该将其设置(修改)为回调。尽管FileReader
继承自EventTarget
,但所有事件(onload,onabort等)都可以与addEventListener
一起使用。因此,在任何情况下,您需要将回调作为事件处理程序传递以进行加载,则可以考虑使用addEventListener。
// method 1
reader.onload = function (e) { ...
// method 2
reader.addEventListener("onload", function (e) { ...