1

Currently, I want to upload some pictures from the frontend to the backend, and I can upload these images correctly, but I don't know how to get these photos in the backend. Here, I upload the images using FormData in the frontend

const url = "http://localhost:5000/hotel";
    const data = new FormData();
    var photos = document.querySelector("input[type='file'][multiple]");
    console.log(photos.files);
    data.append("photos", photos.files);
    fetch(url, {
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      mode: "cors",
      method: "post",
      body: data
    });

now, I tried to get these files in the backend using flask.

@app.route('/hotel', methods=['POST'])
def add_hotel():
    print(request.form)
    print(request.data)
    print(request.files)

The print result is something like this:

ImmutableMultiDict([])
b'------WebKitFormBoundaryo54yZ5CoNX8dQZZ3\r\nContent-Disposition: form-data; name="photos"\r\n\r\n[object FileList]\r\n------WebKitFormBoundaryo54yZ5CoNX8dQZZ3--\r\n'
ImmutableMultiDict([])

and I think these images are stored in the request.data, but how can I save these data like the normal file in request.files?

Neo jin
  • 77
  • 5
  • Possible duplicate of [Uploading multiple files with Fetch and FormData APIs](https://stackoverflow.com/questions/47253661/uploading-multiple-files-with-fetch-and-formdata-apis) – Kent Shikama Oct 28 '19 at 08:53

2 Answers2

1

Actually, I checked my code again, I found that the problem in the frontend, when send request using form data, you should not use the header "Content-Type": "application/json", and just put form data in the body

Neo jin
  • 77
  • 5
0

You have to use request.files.getlist. See /how-to-upload-multiple-files-using-flask-in-python for details and further improvements.

Andi Schroff
  • 1,156
  • 1
  • 12
  • 18
  • Thank you for answering, i found the problem is in the frontend, i should not specify content type when using formdata – Neo jin Oct 29 '19 at 23:14