python form-data post上传数据简便方法

有时要用到 form-data 这种形式post 上传文件到服务器,下面介绍使用python 实现的简便方法。

python form-data post上传数据简便方法

方法一,使用 urllib2 自己打包

自己封装form-data 也很方便

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def test():
    #boundary只要是随机不同的就行
    boundary = '----------%s' % hex(int(time.time() * 1000))
    data = []
    data.append('--%s' % boundary)

    fr=open(r'test2.jpg','rb')
    data.append('Content-Disposition: form-data; name="%s"; filename="new_test2.jpg"' % 'file')
    data.append('Content-Type: %s\r\n' % 'image/jpeg')
    data.append(fr.read())
    fr.close()
    data.append('--%s--\r\n' % boundary)

    #http_url='http://remotserver.com/page.php'
    http_url = 'http://xxx/v1/upload'
    http_body='\r\n'.join(data)
    try:
        #buld http request
        req=urllib2.Request(http_url, data=http_body)
        #header
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)#最重要的一行

        #post data to server
        resp = urllib2.urlopen(req, timeout=5)
        #get response
        qrcont=resp.read()
        print qrcont
    except Exception,e:
        print 'http error'

方法二,使用request

更简洁

1
2
3
4
5
    import requests
        url = 'xxx'
        files={'file':('newname.jpg',open('localname.jpg','rb'),'image/jpeg')}
        rsp=requests.post(url,files=files)
        print(rsp.request.text)

本文网址: https://pylist.com/topic/152.html 转摘请注明来源

Suggested Topics

Python List 按键高效排序方法

Python含有许多古老的排序规则,这些规则在你创建定制的排序方法时会占用很多时间,而这些排序方法运行时也会拖延程序实际的运行速度。...

给ssdb python 接口提速

SSDB 是个新兴的数据库,其数据库的特点简单,性能高效,有好多python 接口,个人比较后选择一个最理想的,但还有提速空间,这里仅作经验分享。...

python 正确计算大文件md5 值

python 计算文件的md5值很方便,但如果只是简单的把文件都入到内存中,大文件会导致问题,一般采用切片的方式分段计算,下面的几个函数可以很好的解决这个问题。...

Leave a Comment