Ramya MiiM
Ramya MiiM

Reputation: 253

FormData is posting only one image file

I want to post multiple image files to the server. I have used formData (formDta.append()) which is getting only one image. it's not taking the multiple images

 **#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)
       })   
}

Upvotes: 1

Views: 761

Answers (2)

Arman Charan
Arman Charan

Reputation: 5797

Your current implementation only attempts to append the first element (0) of imagefile.files.

Array.prototype.forEach() can be leveraged to append each element.

FormData.append() also expects a name as it's first parameter, followed by a value, and lastly an optional filename.

See below for a practical example.

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

Overall, your uploadCategoryImages function could be reduced to the following:

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

Upvotes: 2

Juned Lanja
Juned Lanja

Reputation: 1474

Yes FormData field can be assigned one file at time but you can append multiple file in FormData as below

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

}

Upvotes: 0

Related Questions