Falcon: req.stream.read(), the new file include the WebKitFormBoundary header, it makes my file corrupt

Created on 18 Sep 2017  路  3Comments  路  Source: falconry/falcon

this is my falcon code:

def on_post(self, req, resp, email):
    local_path = create_local_path(req.url, req.content_type)
    with open(local_path, 'wb') as temp_file:
        body = req.stream.read()
        temp_file.write(body)

and the function of create_local_path is to make local_path become a directory_path/filename.ext
And after I checked the new file, it always corrupt. I realize that there is webkitformboundary header after I change the extension of the file to .txt

Do you have any idea how to get this without the header?

For more information, this is the header:

------WebKitFormBoundaryTP8DZAf3SJOvwXWy
Content-Disposition: form-data; name="file"; filename="jpg5.jpg"
Content-Type: image/jpeg

Most helpful comment

Hi, thank you for your help

I manage to get the data without the header by sending the data using object instead of formData. So using req.stream.read() will only read the data without the header.

All 3 comments

Hi @Alfreddatui, it looks like the server is receiving a multipart/form-data body.

Falcon does not currently support parsing files submitted by an HTTP form (multipart/form-data), although we do plan to add this feature in a future version. In the meantime, you can use the standard cgi.FieldStorage class to parse the request:

# TODO: Either validate that content type is multipart/form-data
# here, or in another hook before allowing execution to proceed.

# This must be done to avoid a bug in cgi.FieldStorage
env = req.env
env.setdefault('QUERY_STRING', '')

# TODO: Add error handling, when the request is not formatted
# correctly or does not contain the desired field...

# TODO: Consider overriding make_file, so that you can
# stream directly to the destination rather than
# buffering using TemporaryFile (see http://goo.gl/Yo8h3P)
form = cgi.FieldStorage(fp=req.stream, environ=env)

file_item = form[name]
if file_item.file:
    # TODO: It's an uploaded file... read it in
else:
    # TODO: Raise an error

You might also try this streaming_form_data package by Siddhant Goel.

Thanks!
Such an honour to be replied by the highest contributor of falcon.

Best Regards,
Alfred

Hi, thank you for your help

I manage to get the data without the header by sending the data using object instead of formData. So using req.stream.read() will only read the data without the header.

Was this page helpful?
0 / 5 - 0 ratings