pycurl multipart/form-data 上傳文件並添加自定義字段

比如要發送的數據包如下:

POST /upload.php HTTP/1.1
Host: www.test.com
User-Agent: PycURL/7.43.0 libcurl/7.47.0 OpenSSL/1.0.2e zlib/1.2.8 c-ares/1.10.0 libssh2/1.6.0
Accept: */*
Content-Length: 413
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------66e4a1b668730c47

--------------------------66e4a1b668730c47
Content-Disposition: form-data; name="test1"

value1
--------------------------66e4a1b668730c47
Content-Disposition: form-data; name="test2"

value2
--------------------------66e4a1b668730c47
Content-Disposition: form-data; name="ATTACHMENT"; filename="test.jpg"
Content-Type: image/jpeg

111111111111111111111
--------------------------66e4a1b668730c47--

發送網址:hxxp://www.test.com/upload.php 

參數有三個:

1.名稱 test1 ,值value1

2.名稱 test2 ,值value2

3.名稱 ATTACHMENT ,文件名test.jpg,文件類型image/jpeg 內容假設爲"111111111111111111"

則python腳本爲:

c = pycurl.Curl()
c.setopt(c.URL, 'http://www.baidu.com/upload.php')

c.setopt(c.HTTPPOST, [("test1","value1"),
                      ("test2","value2"),
        ('ATTACHMENT', (
            # upload the contents of this file
            c.FORM_FILE, "./test.jpg",
            # specify a different file name for the upload
            c.FORM_FILENAME, 'test.jpg',
            # specify a different content type
            c.FORM_CONTENTTYPE, 'image/jpeg',
        )),
    ])

c.perform()
c.close()

HTTPPOST選項可以獲取元組列表,每個元組正好有兩個元素長。每個元組的第一個參數是表單字段名,第二個參數是值。 

參考:http://pycurl.io/docs/dev/quickstart.html#sending-form-data

https://stackoverflow.com/questions/679966/problem-with-python-curl-while-submitting-file

https://blog.csdn.net/lacoucou/article/details/56011326

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章