javascript - forEach 不是将多个图像上传到 cloudinary 的函数
问题描述
我正在尝试从我的 Vue2JS 前端将图像上传到 cloudinary。我已经创建了正确上传单个图像的函数,但是在 forEach 循环中上传多个图像时遇到问题。
upload(evt) {
console.log(evt);
let file = evt.target.files;
const formData = new FormData();
formData.append('file', file[0]);
formData.append('upload_preset', this.cloudinary.uploadPreset);
axios.post(this.cloudinary.url, formData)
.then(res => {
console.log(res.data.secure_url);
this.offerData.thumbnail = res.data.secure_url;
}, function (err) {
console.log(err)
});
},
uploadImages(evt) {
console.log(evt);
const formData = new FormData();
evt.forEach(evt.target.files, function (file) {
formData.append('file', file);
formData.append('upload_preset', this.cloudinary.uploadPreset);
axios.post(this.cloudinary.url, formData)
.then(res => {
console.log(res.data.secure_url);
}, function (err) {
console.log(err)
});
})
},
正如我所说,上传功能正常工作。稍后我会将这两个功能合二为一,但只是为了开发,我将它分开,因为第二个功能是 uploadImages 无法正常工作..
evt.target.files
是:
(点击放大)
控制台中显示的错误是:
未捕获的类型错误:evt.forEach 不是函数
我做错了什么?
解决方案
forEach 是 Javascript 数组的一个函数。这看起来像一个 FileList 类型的对象。
您可以使用 for 循环遍历对象键,或者使用 Object.keys() 创建其键的数组,然后遍历这些键。
例如:
uploadImages(evt) {
console.log(evt);
const formData = new FormData();
Object.keys(evt.target.files).forEach(function(key){
let file = evt.target.files[key];
formData.append('file', file);
formData.append('upload_preset', this.cloudinary.uploadPreset);
axios.post(this.cloudinary.url, formData)
.then(res => {
console.log(res.data.secure_url);
}, function (err) {
console.log(err)
});
});
}
推荐阅读
- perforce - Perforce DVCS 解析失败并且 P4 Fetch 与 P4V Fetch 不匹配
- json - 将 JSON 数据发布到 Dotnet Core webapi
- php - Guzzle getTransferTime() 究竟测量了什么?
- asp.net - 客户端 cookie 滑动时刷新 IdentityServer cookie
- gnu-make - make 变量的第二次扩展
- elasticsearch - ElasticSearch:配置 delete_by_query、update_by_query 以重试 version_conflicts
- angular - 从@Input 变量分配的变量也会改变分配的变量
- javascript - 使用 jquery 循环遍历表列以推送到 Google App Script
- ios - 从 tableview Swift 展开时未找到展开 segue
- php - 将 MS SQL 数据库与 MySQL 数据库同步