Flask接受来自HTML表单的文件 - 错误请求

时间:2016-12-21 18:12:07

标签: python html flask

编辑包含第一个答案输入:

我的HTML表单如下所示:

<!DOCTYPE html>
<html>
<body>

<form action="http://localhost:5000/upload_candidates" method='POST' enctype="multipart/form-data">
  <input type="file" name="csv_file" accept="*">
  <input type="submit">
</form>

</body>
</html>

Flask端点如下所示:

@app.route('/upload_candidates', methods=['POST'])
def upload_candidates():
    print('this worked')
    file = request.files['file']
    print('did this work?')
    x = file.read()
    print(x)

if __name__ == "__main__":
    app.run(threaded=True, debug=True)

我收到错误:The browser (or proxy) sent a request that this server could not understand.

在终端:

 * Detected change in '..../hello.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 238-076-488
this worked

在网络控制台中:

Request URL:http://localhost:5000/upload_candidates
Request Method:POST
Status Code:400 BAD REQUEST
Remote Address:127.0.0.1:5000

似乎它不喜欢file = request.files['file']行。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的<form>缺少enctype属性:

<form action="http://localhost:5000/upload_candidates" 
             method="POST" 
             enctype="multipart/form-data">

此外,您似乎使用错误的名称引用request.files成员。试试这个:

file = request.files['csv_file']