python请求上传文件 [英] python requests upload file
本文介绍了python请求上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在访问一个网站,我想上传一个文件.
I'm visiting a website and I want to upload a file.
我用python编写了代码:
I wrote the code in python:
import requests
url = 'http://example.com'
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.content)
但是似乎没有文件上传,页面与初始文件相同.
But it seems no file has been uploaded, and the page is the same as the initial one.
我想知道如何上传文件.
I wonder how I could upload a file.
该页面的源代码:
<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>
推荐答案
几点:
- 确保将您的请求提交到正确的网址(格式为"action")
- 使用
data
参数提交其他表单字段('dir','submit') - 在
files
中包括文件名(这是可选的)
- make sure to submit your request to the correct url ( the form 'action' )
- use the
data
parameter to submit other form fields ( 'dir', 'submit' ) - include the name of the file in
files
( this is optional )
代码:
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)
这篇关于python请求上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文