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 SQLite 数据库提速经验

SQLite 特点是轻巧,依赖少,数据库就一个文件,打包即可提走。最近做一个应用,千万条数据,更新频繁,但处理方式很简单,首先直接用SQLite 处理,结果两分钟可以完成处理一次,这个还是太慢了。下面介绍 SQLite 优化提速的经验。...

3行 Python 代码解简单的一元一次方程

一元一次方程:只含有一个未知数(即“元”),并且未知数的最高次数为1(即“次”)的整式方程叫做一元一次方程(英文名:`linear equation with one unknown`)。...

python 使用 magic 从文件内容判断文件类型

使用 python-magic 库可以轻松识别文件的类型,python-magic是libmagic文件类型识别库的python接口。libmagic通过根据预定义的文件类型列表检查它们的头文件来识别文件类型。 ...

Leave a Comment