使用python请求通过表单数据上传图像 [英] Upload image through form data using python requests
本文介绍了使用python请求通过表单数据上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试自动上传图像.
I am trying to automate uploading of images.
当我在浏览器中上传图像并查看网络"标签时,我在请求正文中看到以下内容:
When I upload an image in the browser and look at the network tab I see te following in request body:
------WebKitFormBoundary053SrPeDVvrnxY3c
Content-Disposition: form-data; name="uploadId"
0:0:48deedc5937d0:1009c3
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="mtype"
1000
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="extensions"
png,gif
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="minPixSize"
1000
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="maxBytesSize"
1000
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="masterSize"
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="masterWidth"
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="masterHeight"
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="imageFile1"; filename="01.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary053SrPeDVvrnxY3g--
我如何在python请求库中重复这样的请求?
How would I repeat such a request with python requests lib?
问题是最后一部分:
------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="imageFile1"; filename="01.jpg"
Content-Type: image/jpeg
所有其他字段只能作为传递给data
参数的dict中的字段添加.
All the other fields can just be added as fields in dict passed to data
parameter.
到目前为止,我已经尝试过:
So far I tried this:
requests.post(
url="http://myserver.com/upload",
headers={
"Content-Type": "multipart/form-data",
},
data={
"uploadId": "0:0:48deedc5937d0:1009c3",
"mtype": "1000",
"extensions": "png,gif",
"minPixSize": "1000",
"maxBytesSize": "1000",
"masterSize": "",
"masterWidth": "",
"masterHeight": ""
},
files={'media': open("01.jpg", 'rb')}
)
服务器回复:
Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found; id: null
推荐答案
此方法有效:
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
multipart_data = MultipartEncoder(
fields={
"uploadId": "0:2d7765623034:557915d737b48:000456",
"mtype": "1000",
"extensions": "png,gif",
"minPixSize": "1000",
"maxBytesSize": "1000",
"masterSize": "",
"masterWidth": "",
"masterHeight": "",
"imageFile1": (
"filename.jpg",
open("filename.jpg"], 'rb'),
"image/jpeg"
)
}
)
requests.post(
url="http://myserver.com/upload",
headers={
"Content-Type": multipart_data.content_type,
},
data=multipart_data,
)
这篇关于使用python请求通过表单数据上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文