Upload image through form data using python reques

2020-08-01 02:32发布

问题:

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--

How would I repeat such a request with python requests lib?

The problem is the last part:

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

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')}
)

Server responded with:

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:

This worked:

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,
)