我是网站开发新手。我使用 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"ˇfˇf> !1AQ"aqÅë° 2B±¡R—·#brÒÇí¢$3Scˇfˇf'!1QAa "#2BqÅˇ⁄ ?“G ÷=`^— Á»÷$ìØxıXä‘Å',5kÔ VãW¶±ÈK@¡tq]~¸¢J^dö±“≈B –Ba.' QoQ∏0dúC•,nı^⁄•1BRâò ´Ô¡C⁄¡XΩ¡Eb & 并继续前进
查看前 3 行,它使文件损坏。
有什么想法吗?
最佳答案
Falcon 不会像您尝试开箱即用那样处理文件上传 - 您需要使用类似 https://github.com/yohanboniface/falcon-multipart 的东西,它提供了处理多部分/表单数据上传的中间件。
您将添加中间件,执行以下操作:
from falcon_multipart.middleware import MultipartMiddleware # pip install falcon-multipart
api = falcon.API(middleware=[MultipartMiddleware()])
您可能想要更改您的前端代码(请参阅 How do I POST with multipart form data using fetch? ),尽管我不确定您正在使用什么框架。
完成此操作后,您最终可能会得到看起来更像的处理程序代码(假设您在名为“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)
关于Python从POST请求接收formData,获取流,文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46271936/