• 欢迎访问IT乐园(o゚▽゚)o
  • 推荐使用最新版火狐浏览器和Chrome浏览器访问本网站。

python的requests模块多文件上传

python fhy 7年前 (2017-04-11) 10828次浏览 0个评论
文章目录[隐藏]

Documenthere):

POST Multiple Multipart-Encoded Files
You can send multiple files in one request. For example, suppose you want to upload image files to an HTML form with a multiple file field ‘images’:

<input type="file" name="images" multiple="true" required="true"/>

To do that, just set files to a list of tuples of (form_field_name, file_info):

>>> url = 'http://httpbin.org/post'
>>> multiple_files = [
        ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
        ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
>>> r = requests.post(url, files=multiple_files)
>>> r.text
{
  ...
  'files': {'images': 'data:image/png;base64,iVBORw ....'}
  'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',
  ...
}

Warning

It is strongly recommended that you open files in binary mode. This is because Requests may attempt to provide the Content-Length header for you, and if it does this value will be set to the number of bytes in the file. Errors may occur if you open the file in text mode.

TEST:

#!/usr/bin/python3
#-*- coding:utf-8 -*-

import requests
import json
import os
import sys

def getfile(ppath):
    pfile = os.listdir(ppath)
    return pfile

def uptest(par=''):
    url = "" # Request URL
    post = {"json_msg": json.dumps( \
        {"function_name":"upload_proprietor_msg", 
         "params":{"yz_tel" : "",
                   "qy_num" : "19000",
                   "zx_address" : "分享",
                   "qy_firm" : "10000",
                   "yz_is_tg" : 0,
                   "qy_time" : "2017-04-07",
                   "yz_name" : "测试 1",
                   "token" : "30bb34e0-7058-7d7e-28e1-14d63187b44c",
                   "designer_id" : "4"}} )}
    
    # pic test
    ppath = '/home/fhy/'
    files = [
        ('file[]', ('fluidicon.png', open(ppath+'fluidicon.png', 'rb'), 'image/png')),
        ('file[]', ('qq.jpg', open(ppath+'qq.jpg', 'rb'), 'image/jpg'))]
    
    rs = requests.post(url, files=files, data=post)
   
    # formatting
    if par == 'f':
        print('formatting')
        jsonen = rs.content.decode('utf-8-sig')
        strj = json.loads(jsonen)
        # print (strj)
        print( json.dumps(strj, ensure_ascii=False, indent=4, sort_keys=True) )
        sys.exit()

    print(rs.text)
    # print('fhy'*3)

uptest()

注意

当时测试遇到只能上传一张的问题,琢磨了好久,仔细一想 html 的 file 标签上传时加”[]”才能实现多图。故将 file 改为 file[]


IT 乐园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python 的 requests 模块多文件上传
喜欢 (4)
关于作者:
九零后挨踢男
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址