0

Without a form I am trying to post multiple files to my server using AJAX.

This is the input file

<input id="images_input" type="file" name="images" multiple="" class="inputFileHidden"> 

The result I receive after pressing on the submit button is a FileList, as shown down below.

enter image description here

I stringify my File objects and sending my data through a FormData object under the picture_files key.

var data = new FormData()
files = document.getElementById('images_input').files
...
Array.from(files).forEach(file => data.append('picture_files', JSON.stringify(file)))

The problem I have on my Server Side after I request the key from the request.form object is that I get an empty object

images = request.form['picture_files']
print(images) # result is {}

Any hints on how I can safely JSON.stringify my javascript objects to my server?

netlemon
  • 964
  • 8
  • 22
  • Does [this](https://stackoverflow.com/questions/24139216/js-input-file-to-json-with-for-example-json-stringify) answer your question? – lusc Jul 06 '20 at 17:54
  • @gre_gor close enough..interesting approach. Didn't know that the Files were actually pointers. Thanks for the insight – netlemon Jul 06 '20 at 18:04

1 Answers1

0

You can't simply convert a file object into JSON.

You could use FileReader to read the file, convert it into a string (e.g. using Base64 encoding), put that string in an object, then encode the object as JSON. This would be complicated and inefficient.

It would be far simpler to just put the file object into the FormData as it is.

Array.from(files).forEach(file => data.append('picture_files', file))
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • By doing that I can't retrieve my files by accessing `request.form['picture_files']`, quite interesting..but if I leave it as it was, it works. This being the stacktrace `400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'picture_files'` – netlemon Jul 06 '20 at 18:00
  • https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/ – Quentin Jul 06 '20 at 18:04
  • I've changed my code to `images = request.files.getlist('images_input')` which works, but it returns an empty list now `[]`. That makes sense since the `File` objects are not objects, but pointers. So I don't think this method would work, my humble opinion. – netlemon Jul 06 '20 at 18:07