3

I want to pass a uploaded file from multipart/form-data directly to my DLL function, without saving it as a temporary file.

My c-style DLL function looks like:

int process_image(unsigned char* image, int size);

The argument "image" is expected to be a binary array containing the complete data of a jpeg file, and the argument "size" is the size of "image". Since this data is exactly a part of the multipart/form-data, I want to extract it and pass it directly to the DLL function using Flask and ctypes.

But after I looked into Flask, I found Flask extracts the files from multipart/form-data as FileStorage objects (request.files) like:

@app.route("/", methods=['POST'])
def getimages():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

So my questions are:

  1. How can I get the binary image (jpeg) data from multipart/form-data using Flask?
  2. Then how can I convert this binary data using ctypes and pass it directly to my DLL function?
bneely
  • 9,083
  • 4
  • 38
  • 46
volvic
  • 39
  • 1
  • 4

1 Answers1

2

I can only partially answer your question.

For first part use:

f = request.files['file']
bin_file = StringIO.StringIO(f.read())  # or ByteIO, whatever you like
# Now you have file in memory as binary
# I recommend using bin_file.seek(0) before every read/modification/write

I have very limited experience with C and DLL-like code. So I can't give you direct solution. But I can give you some hints how would I solve it.

One of the solution could be passing StringIO/ByteIO as an argument to C/C++ program. I would try using python's subprocess.

Another solution would be writing a python wrapper for your code, calling it directly in python/flask. Again, I have no experience with it.

gcerar
  • 920
  • 1
  • 13
  • 24