If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script.
You mean like:
return send_file('path/to/file.png')
That works, because Flask's send_file
function actually returns a Response
object.
This is also valid code (as of flask version 1.1.0
):
return {"message" : "File not found!"}, 404
Here you're returning a dictionary with the key 'message'
and value 'File not found!'
. Flask will turn this into a Response
object, with a status code of 404
.
That dictionary is jsonified automatically (as of flask version 1.1.0
).
When you try to return this:
return {"file1" : send_file('uploads/kode.png')}, 200
The Response
object returned by send_file
is then jsonified, hence the exception:
TypeError: Object of type 'Response' is not JSON serializable
The obvious way to make this work is that the frontend should make a separate request to the server for each image, passing some kind of ID which the Flask route function should then obtain and use to work out the filepath, then ultimately: return sendfile(filepath)
.
If you really want to send several images in one JSON response, you could look at base64 encoding the image and making a data_uri string which can be JSON serialized. However unless you really need that data to be passed as JSON, the former option is probably the go-to.