vuejs2 - Vue 和 FileReader API:如何在上传之前等待图像文件?
问题描述
我正在尝试使用 FileReader() API,但无法理解如何等待它完成,以便我可以访问数据 URL 并将其上传到云存储。
让我解释:
我有以下模板:
<input
id="my-file-input"
type="file"
accept="image/*"
@change="fileChangeHandler"
/>
<img src="photo" />
脚本:
fileChangeHandler(e) {
const reader = new FileReader()
reader.onload = (e) => {
this.photo = e.target.result
}
reader.readAsDataURL(e.target.files[0])
console.log(this.photo)
const file = this.photo
// convert photo file name to hash
const photoName = uuidv4()
const storageRef = this.$fireStorage.ref()
const photoRef = storageRef.child(
`photos/${this.userProfile.uid}/${photoName}/${photoName}.jpg`
)
const uploadTask = photoRef.putString(file, 'data_url') <--- image not ready yet, thus get console error
在运行之前如何成功等待文件阅读器完成.putString()
?谢谢!
解决方案
您可以使用 aPromise
然后使用async await
如下:
async fileChangeHandler(e) {
this.photo = await new Promise(resolve=>{
const reader = new FileReader()
reader.onload = (e) => {
resolve(e.target.result)
}
});
// rest of your code
}
推荐阅读
- node.js - 如何从新创建的数据库条目中获取 ID 以进行重定向 - Mongoose
- javascript - 无法使用 $push 更新 Mongo DB 对话集合
- android - 与滑动相反的方向滚动(cordova android webview)
- java - 根据使用 Thymeleaf 选择的选择选项更改 HTML 表单布局
- python - 带参数的生成器?
- flutter - 找不到框架flutter_plugin_android_lifecycle颤振
- python - 正则表达式在数字范围内查找匹配项
- c# - 有没有办法让一个类知道订阅它的委托的东西成功运行了?
- jquery - 我想在 jQuery Datepicker 中禁用特定的假期和星期几
- typescript - 如何使用 Angular 10 实现拖放流程图?