[英]python requests upload file
我正在访问一个网站,我想上传一个文件。
我用python编写了代码:
import requests
url = 'http://example.com'
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.content)
但是似乎没有文件上传,页面与初始页面相同。
我不知道如何上传文件。
该页面的源代码:
<html><head><meta charset="utf-8" /></head>
<body>
<br><br>
Upload<br><br>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="hidden" name="dir" value="/uploads/" />
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
几点:
data
参数提交其他表单字段('dir','submit') files
(这是可选的) 代码:
import requests
url = 'http://example.com' + '/upload.php'
data = {'dir':'/uploads/', 'submit':'Submit'}
files = {'file':('1.jpg', open('1.jpg', 'rb'))}
r = requests.post(url, data=data, files=files)
print(r.content)
首先,定义上传目录的路径,例如
app.config['UPLOAD_FOLDER'] = 'uploads/'
然后定义允许上传的文件扩展名,
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
现在假设您调用函数来处理上传文件,那么您必须编写类似以下的代码,
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename))
这样,您可以上传文件并将其存储在您所找到的文件夹中。
我希望这能帮到您。
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.