首页 > 解决方案 > 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是:

alt

(点击放大)

控制台中显示的错误是:

未捕获的类型错误:evt.forEach 不是函数

我做错了什么?

标签: javascriptvue.jsuploadvuejs2cloudinary

解决方案


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

推荐阅读