使用Python的Requests模块将文件上传到Flask服务器时遇到问题。
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/Upload/'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
我可以通过网页上传文件,但我想上传带有这样的请求模块的文件:
import requests
r = requests.post('http://127.0.0.1:5000', files={'random.txt': open('random.txt', 'rb')})
它一直返回400并说#34;浏览器(或代理)发送了一个请求,该服务器无法理解&#34;
我觉得我错过了一些简单的事情,但我无法理解。
答案 0 :(得分:0)
您将文件上传为random.txt
字段:
files={'random.txt': open('random.txt', 'rb')}
# ^^^^^^^^^^^^ this is the field name
但请查找名为file
的字段:
file = request.files['file']
# ^^^^^^ the field name
让那两场比赛;使用file
作为files
字典,例如:
files={'file': open('random.txt', 'rb')}
请注意requests
会自动检测该打开文件对象的文件名,并将其包含在部分标题中。
答案 1 :(得分:0)
因为您<input>
name=file
所以需要
files={'file': ('random.txt', open('random.txt', 'rb'))}
请求文档中的示例:POST a Multipart-Encoded File