2017-08-25 74 views
1

我試圖自動上傳圖像。使用python請求通過表單數據上傳圖像

當我在瀏覽器中上傳圖片,並期待在網絡選項卡中我看到TE按照請求正文:

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

回答

2

這工作:

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