1

我是网站开发的新手。我使用 React-Redux 和 Python 作为我的后端(Falcon 框架),我所做的是:

1) 从前端接收一个 formData(),使用 Dispatch 到 POST :

我的调度代码:

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

并使用中间件,仅调用函数 POST:

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

和我的获取功能:

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())
}

和我的后端,使用 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)

问题是创建了 temp_file 但它已损坏,并且在我将扩展名更改为 txt 文件之后。它应该用一些只有计算机才能理解的奇怪代码编写。但是有些行会使整个文件损坏。请帮忙。这是txt文件的样子:

------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 & 并继续前进

查看前 3 行,它使文件损坏。

任何想法 ?

4

1 回答 1

0

Falcon 不像您尝试开箱即用那样处理文件上传 - 您需要使用类似https://github.com/yohanboniface/falcon-multipart的东西,它提供了处理 multipart/form-data 的中间件上传。

您将添加中间件,执行以下操作:

from falcon_multipart.middleware import MultipartMiddleware

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

您可能想要更改您的前端代码(请参阅fetch post with multipart form data),但我不确定您使用的是什么框架。

一旦你这样做了,你最终可能会得到看起来更像的处理程序代码(假设你在一个名为“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)
于 2017-10-09T22:23:43.290 回答