Python receive formData from POST request, get the stream, File Corrupt

1.5k Views Asked by At

I am new to Website Development. I am using React-Redux, and Python as my backend(Falcon framework) and what I did were:

1) Receive a formData() from frontEnd, using Dispatch to POST :

my Dispatch code:

this.props.dispatch({type: ActionTypes.FILE_UPLOAD_REQUEST, email: this.state.email, file: this.state.policyFile});

and using middleware, only to call function POST:

var result = yield call(Atlas.uploadFile, action.email, action.file);

and my fetch function:

export const uploadFile = (email, file) => {
    console.log(file);
    return fetch(`${BASE_URL}/v1/files/${email}/policies`, {
        method: 'POST',
        body: file,
        headers:{}
    })
    .then(response => response.json())
}

and my backend side, using falcon API:

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)

The problem is the temp_file is created but it is corrupted and after I change the extension to txt file. It should be written in some strange code that only computer understand. BUT the are some lines that make the entire file corrupted. please help. this is the txt file looks like:

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

ˇÿˇ‡JFIFˇ€Ñ   ( %!1"%)+...383-7(-.+

-%---------------.----------------------------7----- ˇ¿„fi"ˇƒˇƒ>!1AQ"aqÅë°2B±¡R—·#brÒÇí¢$3Scˇƒˇƒ'!1QAa"#2BqÅˇ⁄?“G ÷=`^— Á»÷$ìØxıXÄ‘Å'‚ 5kÔVãW¶±ÈK@¡tq]~¸¢J^dö±“≈B–Ba.'QoQ∏0dúC•,nı^⁄•1BR¢âò ´Ô¨C⁄ƒXΩ¡ ¨Eb & and keep going

Look at the first 3 line, it make the file corrupted.

Any idea ?

1

There are 1 best solutions below

0
On

Falcon doesn't handle file uploads like you're trying to do out of the box -- you need to use something like https://github.com/yohanboniface/falcon-multipart, which provides middleware to handle multipart/form-data uploads.

You'll add the middleware doing something like:

from falcon_multipart.middleware import MultipartMiddleware  # pip install falcon-multipart

api = falcon.API(middleware=[MultipartMiddleware()])

You'll probably want to alter your frontend code (see How do I POST with multipart form data using fetch?), though I'm not sure exactly what framework you're using.

Once you've done so, you might end up with handler code that looks more like (assuming you're passing the file in a form field called "image"):

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.get_param('image')
        temp_file.write(body)