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

问题描述 投票:0回答:2

我正试图从我的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

(点击将其放大)

和控制台中显示的错误是:

未捕获的TypeError:evt.forEach不是函数

我做错了什么?

javascript vue.js upload vuejs2 cloudinary
2个回答
1
投票

问题是你试图在forEach上执行Event方法,但Event没有forEach方法

即使你试图用evt.target.files做,这是一个FileList,并没有forEach方法

借鉴了AJD的答案,进行了以下修改

  • 使用Object.values而不是Object.keys - 从不对密钥感兴趣,所以这消除了对let file = evt.target.files[key]的需要
  • 修复formData可能存在的问题 - 你继续在循环中添加一个 - 我宁愿为每个循环创建一个新的
  • 修复this被“丢失”(使用箭头功能)

然后代码变成了

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

1
投票

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)
            });
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.