forEach 不是将多个图像上传到 cloudinary 的函数

forEach is not a function uploading multiple images to 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 是:

(点击放大)

控制台中显示的错误是:

Uncaught TypeError: evt.forEach is not a function

我做错了什么?

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

问题是您正在尝试对 Event 执行 forEach 方法,但 Event 没有 forEach 方法

即使您尝试使用 evt.target.files 来实现,那也是 FileList,并且没有 forEach 方法

借用 AJD 的答案,并进行了以下更改

  • 使用 Object.values 而不是 Object.keys - 对密钥不感兴趣,因此不需要 let file = evt.target.files[key]
  • 修复了 formData 可能存在的问题 - 你在循环中不断添加一个 - 我宁愿为每个循环创建一个新的
  • 修复 this 为 "lost"(通过使用箭头函数)

代码则变为

uploadImages(evt) {
    Object.values(evt.target.files).forEach(file => {
        const formData = new FormData();
        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);
            }, err => {
                console.log(err)
            });
    });
}