React: FormData not sending image data to Flask backend

Viewed 478

I am trying to upload an image, but the form data simply doesn't append the file data to my request.

Front end:

const form = new FormData()
form.append('files[]', file)
form.append("woor","w")
console.log(file)
const header = {
     headers: { 'Content-Type': 'multipart/form-data'}
}
axios.post(
   action,
   form,
   header
).then(({ data: response }) => {})

Flask backend:

def upload():
    print(request.form)
    print(request.json)    
    return {"body":[{"value":"fdd", "label":"fdaad"}]}

The backend prints out ImmutableMultiDict([('woor', 'w')]) but not the file, console.log does show the file data I have also tried {"file":file} and {"file[]":file}

EDIT: file is not an array. It looks like a dict to me from console.log()

3 Answers

I recently came across the same Issue, the answer might be suprisingly simple, you access the file with request.files instead of request.form in flask.
Here is also a link to the SO question where I had the same Issue, figured it out after a few days: Dropzone.js not sending the file when adding additional data

The file object that you are passing to append form must be not correct .yourFileInputField.files gives you the array of selected files.
For Single File

let files=yourFileInputField.files; //returns the list of files
form.append('files', files[0])

for Multiple files

let files=yourFileInputField.files; //returns the list of files

files.forEach(function(file,index){
  form.append('files['+index+']',file)
})

As I have checked that many are facing this issue. In my case, I had multiple header parameter where payload was in formData. So I used this approach:

      let formData = new FormData();
      if(e && e[0]){
        formData.append('file', e[0])
      }
    
      const updatePromise = props.uploadImage(formData, payload);
      updatePromise.then((res: any) => {
        props.getEntry({ id: params.id });
      });
      return updatePromise; 
Related