The objects in request.files are FileStorage objects. They have the same methods as normal file objects in python.

So, to get the contents of the file as binary, just do this:

data = request.files['file'].read()

Then pass that parameter into the INSERT.

Answer from Steven Kryskalla on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 57844257 › why-is-binary-data-posted-to-flask-app-different
python - Why is binary data posted to flask app different? - Stack Overflow
September 9, 2019 - import requests import os data = None with open("infile.pdf", "rb") as infile: data = infile.read() print("length of input data: {}".format(len(data))) print("first 40: {}".format(data[:40])) the_url = os.environ['BASE_DOMAIN'] + "/binary" res = requests.post(url=the_url, data=data, headers={'Content-Type': 'application/octet-stream'})
Discussions

writing python request using "post" to flask server as binary file - Stack Overflow
My client use this code to upload file and some json to a flask server : datas = {'CurrentMail': "AA", 'STRUserUUID1': "BB", 'FirstName': "ZZ", 'LastName': "ZZ", 'EE': "RR", 'JobRole': "TT" ... More on stackoverflow.com
🌐 stackoverflow.com
January 5, 2018
How to upload image file via binary file Not using form-data
Import StringIO, create stream then write to this stream from request.stream. Then call yourstream.getValue() to get binary data and save it. Maybe I forgot how this methods called exactly, but main idea the same. More on reddit.com
🌐 r/flask
2
3
June 21, 2018
python - Flask to return image stored in database - Stack Overflow
However, it seems that I can't return binary directly in Flask? My idea so far: Return the base64 of the image binary. The problem is that IE<8 doesn't support this. Create a temporary file then return it with send_file. More on stackoverflow.com
🌐 stackoverflow.com
python - Posting binary file and name in the same request in AngularJS and Flask - Stack Overflow
I am trying to upload (post) a file and its filename in the same request in angular and then receive it in Flask and write to disc. More on stackoverflow.com
🌐 stackoverflow.com
July 19, 2016
🌐
GitHub
gist.github.com › yoavram › 4351498
Example of uploading binary files programmatically in python, including both client and server code. Client implemented with the requests library and the server is implemented with the flask library. · GitHub
Example of uploading binary files programmatically in python, including both client and server code. Client implemented with the requests library and the server is implemented with the flask libra...
🌐
Stack Overflow
stackoverflow.com › questions › 48116820 › writing-python-request-using-post-to-flask-server-as-binary-file
writing python request using "post" to flask server as binary file - Stack Overflow
January 5, 2018 - # test 1 foo = request.get_data() #TEST 2 foo = request.files #test 3 foo = request.stream.read() f = request.files['file'] fname = f.filename #Using Hexa for the binary name and prefix bin fname_hexa = fname.encode("hex") bin_file_name="%s_%s"%("bin",fname_hexa) with open(bin_file_name, 'wb') as output_file_bin: output_file_bin.write(**foo**) output_file_bin.close() But I get an empty file whatever the method used to right "foo" : get_data() and stream.read() If I use only "files", I got an error message from my flask server :
🌐
GitHub
gist.github.com › Miserlou › fcf0e9410364d98a853cb7ff42efd35a
Flask serving binary data example · GitHub
You could simply give the bites object to send_file() instead of re-wrapping it in io.BytesIO().
🌐
Pelicandd
blog.pelicandd.com › article › 80
Streaming input and output in Flask
Here's an ex­am­ple where the in­put stream is copied to a file with no mem­o­ry foot­print: @flask.route("", methods=["POST"]) def demo(): with open("/tmp/flask-stream-demo", "bw") as f: chunk_size = 4096 while True: chunk = flask.request.stream.read(chunk_size) if len(chunk) == 0: return f.write(chunk)
Find elsewhere
🌐
Alexsm
alexsm.com › flask-serve-images-on-the-fly
alexsm@home | Serve images on the fly in a binary form with Flask
May 1, 2021 - import flask import cv2 app = flask.Flask(__name__) def get_image_path(id): # ... build the full path return image_path @app.route('/image/<int:id>') def serve_image(id): # Get the full image path image_path = get_image_path(id) # Read the original image im = cv2.imread(fname, cv2.IMREAD_ANYCOLOR) # Resize the image (here make it 9 times smaller) new_shape = (im.shape[1] // 3, im.shape[0] // 3) im_smaller = cv2.resize(im, new_shape) # Encode the resized image to PNG _, im_bytes_np = cv2.imencode('.png', im_smaller) # Constuct raw bytes string bytes_str = im_bytes_np.tobytes() # Create response given the bytes response = flask.make_response(bytes_str) response.headers.set('Content-Type', 'image/png') return response
🌐
GitHub
gist.github.com › jarlostensen › 7cf211dc763c83e7f22c4ec8c729986c
python Flask POST binary float array using numpy · GitHub
python Flask POST binary float array using numpy · Raw · client_side.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Stack Overflow
stackoverflow.com › questions › 38453912 › posting-binary-file-and-name-in-the-same-request-in-angularjs-and-flask
python - Posting binary file and name in the same request in AngularJS and Flask - Stack Overflow
July 19, 2016 - // Send file as Blob along with its filename $http({ url: baseUrlService.baseURL + 'importtifile', method: 'POST', headers: {'Content-Type': undefined}, data: { filedata: fileBlob }, uploadEventHandlers: { progress: function(e) { importData.fileUploadProgress = e; console.log(importData.fileUploadProgress); } }, transformRequest: function (data, headersGetter) { var formData = new FormData(); formData.append('fileblob', data.filedata); return formData; } }).then( ... In the flask part one can extract both file blob and name:
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › handling-file-uploads-with-flask
Handling File Uploads With Flask - miguelgrinberg.com
July 8, 2020 - Note how the same root URL is split between two view functions, with index() set to accept the GET requests and upload_file() the POST ones. The uploaded_file variable holds the submitted file object. This is an instance of class FileStorage, which Flask imports from Werkzeug.
🌐
Stack Overflow
stackoverflow.com › questions › 45214871 › post-binary-data-to-flask-and-save-it-to-xlsx-produces-corrupted-file
node.js - Post binary data to flask and save it to xlsx produces corrupted file - Stack Overflow
July 20, 2017 - Please note that if i write the file with node, it's readable and fine, and the console.log() and print both display the same body data, it's just the writnig to the file that doesn't seem to go well for me. ... r.get({url : link, encoding: 'binary'}, function (error, res, body) { if(err) console.log(err); else { console.log("requesting data transformation"); request.post({url : "http://127.0.0.1:5000/app_name/api/v1.0/transform", body : body} , function (error, res, json_body) { console.log("requesting"); console.log(json_body) }); } }) ... from flask import Flask, request app = Flask(__name__) @app.route('/app_name/api/v1.0/transform', methods=['POST']) def transform(): print request.get_data() with open('binaryxl.xlsx', 'wb') as output_file: output_file.write(request.get_data()) output_file.close() return "ok" if __name__ == '__main__': app.run(debug=True, port=5000)
🌐
FastAPI
fastapi.tiangolo.com › tutorial › request-files
Request Files - FastAPI
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: bytes = File()): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename} Using UploadFile has several advantages over bytes: You don't have to use File() in the default value of the parameter. ... A file stored in memory up to a maximum size limit, and after passing this limit it will be stored in disk. This means that it will work well for large files like images, videos, large binaries, etc.
🌐
Luisrei
blog.luisrei.com › articles › flaskrest.html
Implementing a RESTful Web API with Python & Flask - Luis Rei
May 2, 2012 - POST /messages {"message": "Hello Data"} Content-type: application/json JSON Message: {"message": "Hello Data"} POST /message <message.bin> Content-type: application/octet-stream Binary message written! Also note that Flask can handle files POSTed via an HTML form using request.files and curl can simulate that behavior with the -F flag.
🌐
Reddit
reddit.com › r/reactjs › display image from flask send_file function
r/reactjs on Reddit: Display image from flask send_file function
April 28, 2019 -

Hi there,

I am trying to display an image that is sent from a flask backend using Flask's 'send_file' function. I believe send_file sends the image back as binary data. I am trying to use this response to create a new blob and display it on the screen for the user.

My react code:

let matrixData = response; //The response from flask's send_file
console.log(response); 
let matrixBlob = new Blob([matrixData.data], {type:"image/jpg"}); 
console.log(matrixBlob);
let fileReader = new FileReader();
fileReader.readAsDataURL(matrixBlob); 
fileReader.onload = () => { 
    let result = fileReader.result; console.log(result); 
    this.setState({ confusionMatrix: result
 }); 
}

The response data looks like this:

{data: "����JFIFdd��C…��↵(��↵(��↵(��↵(��↵(��↵(��↵(��↵(��↵(��↵(��↵(��?��", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: "����JFIFdd��C"
headers: {last-modified: "Sun, 28 Apr 2019 20:34:17 GMT", content-type: "blob", cache-control: "public, max-age=43200", expires: "Mon, 29 Apr 2019 08:34:17 GMT"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object

my result from fileReader looks like this(truncated for posting purposes):

data:image/jpg;base64,77+977+977+977+9ABBKRklGAAEBAQBkAGQAAO+/ve+/vQBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgrvv73vv70AQwECAgICAgIFAwMFCgcGBwoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoK77+977+9ABEIAe+/vQLvv70DASIAAhEBAxEB77+977+9AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC++/ve+/vQDvv70QAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQy77+977+977+9CCNC77+977+9FVLvv73vv70kM2Jy77+9CQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eu+/ 

Just in case, the flask code that sends the file:

return send_file('confusion_matrix.jpg', mimetype='image/jpg')

When I look at the preview of the response in my Developer tools, I can see the image, but I guess I'm not converting it in a way that React expects?

EDIT: Code formatting

Top answer
1 of 2
1
Looks all ok, the problem is probably in the code you didn't show us. (But I would generally use GET endpoints for retrieving images so they can be directly viewed and embedded)
2 of 2
1
I use almost the same code to fetch pdf from mongo (similar as in my request contains a binary) the answer given by the user sayin it's most likely somewhere in the code you didn't show us, i agree, i use fetch() API, to get my file, and when you receive a mime-type: application/pdf, one must use response().blob() and not response.json(), you're sayin you're using axios, maybe you need to set some parameters so it will handle file response as you'd want it to. Here's the code to illustrate, // Client Side const response = await this.props.appActions.fetchFileFromMongo(filename) const blob = new Blob([response], { type: 'application/pdf' }) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = \${type}-${filename}.pdf`setTimeout(() => {link.click()this.setState({ loading: false })}, 1000)// behind the scene the fetchAsync function executing the actual requestconst response = await fetch(url, {mode: 'cors',type: 'json',headers: new Headers({Accept: 'application/json','Content-Type': 'application/json','X-Access-Token': localStorage.getItem('token')}),...options})` await response.json() <- this will fail // this will work data = await response.blob() // Server side async fetchById (req) { const file = await File.findOne({ _id: req.params.file_id }).lean() if (!file) throw new Error('File not found') return { data: file.file, setHeader: ['content-type', 'application/pdf'] } }