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://py.youbbs.org/topic/152.html 转摘请注明来源

Suggested Topics

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

python 对中文链接安全转码

当一个链接里包含中文时,有些浏览器并不能正确解析,这就需要首先对中文作安全转码,这里介绍用 python 对中文链接安全转码,...

python编程中常用的12种基础知识总结

python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。...

Openresty使用lua-resty-upload模块上传并保存文件

OpenResty 是一个基于 Nginx 与Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。这里将用到 lua-resty-upload 模块来处理上传超大的文件的请求。...

Leave a Comment