【问题标题】:FormData is posting only one image fileFormData 仅发布一个图像文件
【发布时间】:2018-10-11 05:20:50
【问题描述】:

我想将多个图像文件发布到服务器。我使用了 formData (formDta.append()),它只得到一张图像。它没有拍摄多张图片

 **#contained-button-file** is the input file ID

uploadCategoryImages = () => {
    let formData = new FormData()
    let imagefile = document.querySelector('#contained-button-file')
    formData.append('image', imagefile.files[0])
    api.post('/api/v1/addimage/category/3', formData)
       .then(function (response) {
           console.log(response)
       })
       .catch(function (error) {
           alert(error)
       })   
}

【问题讨论】:

    标签: javascript reactjs form-data


    【解决方案1】:

    您当前的实现仅尝试附加 imagefile.files 的第一个元素 (0)。

    Array.prototype.forEach() 可以用来附加每个元素。

    FormData.append() 还需要一个名称作为它的第一个参数,然后是一个值,最后是一个可选的文件名。

    请参阅下面的实际示例。

    [...imagefile.files].forEach(file => formData.append('image[]', file))
    

    总体而言,您的uploadCategoryImages 函数可以简化为以下内容:

    uploadCategoryImages = () => {
      const data = new FormData()
      const images = document.getElementById('contained-button-file').files
      [...images].forEach(image => data.append('image[]', image))
      api.post('/api/v1/addimage/category/3', data)
        .then(console.log)
        .catch(alert)
    }
    

    【讨论】:

    • 我收到“imagefile.files.forEach 不是函数”这个错误
    • 我的错。 filesFileList(不是数组),因此需要强制转换(使用 spread syntaxArray.from() @RamyaMiiM
    • ^(为了使用Array.prototype.forEach()) - 否则forfor...of 语句就足够了。
    • 无法在 formdata 中附加多个图像
    • 我已将答案中的名称参数修改为'image[]'this example 的第三个 sn-p 建议它应该可以工作 @RamyaMiiM
    【解决方案2】:

    是的FormData 字段一次可以分配一个文件,但您可以在FormData 中附加多个文件,如下所示

    uploadCategoryImages = () => {
     let formData = new FormData();
     let imagefile = document.querySelector('#contained-button-file');
    
     //loop through file elements and append file in formdata
     for(var i = 0; i <imagefile.files.length; i++){
        //you can name it anything here it will be image-0, image-1 like so
        formData.append('image-'+ i, imagefile.files[i]);
     }
    
     api.post('/api/azz/a/ss/ss/ss/s/', formData)
     .then(function (response) 
      {
      console.log(response)
      alert("Images have been uploaded Succesfully!!!");
      })
      .catch(function (error) {
      alert(error)
      })
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      相关资源
      最近更新 更多