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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thank you for answering, i found the problem is in the frontend, i should not specify content type when using formdata

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.