使用python请求通过表单数据上传图像

时间:2017-08-25 12:51:51

标签: python file-upload request multipartform-data

我正在尝试自动上传图片。

当我在浏览器中上传图像并查看网络标签时,我在请求正文中看到以下内容:

------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请求lib重复这样的请求?

问题是最后一部分:

------WebKitFormBoundary053SrPeDVvrnxY3g
Content-Disposition: form-data; name="imageFile1"; filename="01.jpg"
Content-Type: image/jpeg

所有其他字段只能作为传递给data参数的字典中的字段添加。

到目前为止,我试过这个:

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

1 个答案:

答案 0 :(得分:3)

这有效:

if lstPoint.count != 0,
    let lastTag = lstTagImage.last {
    lstPoint.remove(at: lstPoint.count - 1)
    lstTagImage.removeLast()

    let imageView = view.viewWithTag(lastTag)
    imageView.removeFromSuperview()
}