python使用requests实现发送带文件请求
创始人
2024-03-18 16:29:46

1. requests发送文件功能

Requests 使得上传多部分编码文件变得很简单

url = 'http://httpbin.org/post'
files = {'file': open('D:/APPs.png', 'rb')}
r = requests.post(url, files=files)
print(r.text)


你可以显式地设置文件名,文件类型和请求头:

url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
print(r.text)


如果你想,你也可以发送作为文件来接收的字符串:

url = 'http://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}r = requests.post(url, files=files)
print(r.text)

如果你发送一个非常大的文件作为 multipart/form-data 请求,你可能希望将请求做成数据流。默认下 requests 不支持, 但有个第三方包 requests-toolbelt 是支持的。你可以阅读 toolbelt 文档 来了解使用方法。

2. requests发送多个文件请求

只要把文件设到一个元组的列表中,其中元组结构为 (form_field_name, file_info)
按照如下格式发送数据
data = {'ts_id': tsid}
files = [('images',('1.png', open('/home/1.png', 'rb'),'image/png')),('images',('2.png', open('/home/2.png', 'rb'),'image/png'))]
r = requests.post(url, data=data, files=files)
print r.text

3. Django 接收文件

附带介绍Django里面如何接收图片文件数据:
读取文件:
from werkzeug.utils import secure_filename
 
def upload_file(request):
    if request.method == 'POST':
        uploaded_files = request.FILES.getlist("images")
        try:
            for file in uploaded_files:
                filename = secure_filename(file.name)
                handle_uploaded_file(os.path.join(ft, filename), file)
        except Exception as e:
            result_json = {"msg": str(e)}
        result = {
            'json': result_json
        }
        return JsonResponse(result, safe=False)

保存文件:
def handle_uploaded_file(filename, f):
    try:
        destination = open(filename, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    except Exception as e:
        raise Exception('save %s failed: %s' % (filename, str(e)))


requests 官网:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#post-multipart-encoded
 

相关内容

热门资讯

农技专家 科技服务稳生产 (来源:衢州日报)转自:衢州日报  本报讯 (报道组 郑晨 通讯员 童媛媛 刘烨珏 王卉) 近日寒潮...
新疆农村居民人均可支配收入 首... (来源:劳动午报)转自:劳动午报 新华社电 2025年,新疆城乡居民人均可支配收入分别增长5.3%、...
“万千星火护春运 法治同行守平... (来源:劳动午报)转自:劳动午报 昨天,由北京市天康戒毒康复所联合北京铁路公安局北京公安处北京西站派...
漂莱特创下衢州新速度 (来源:衢州日报)转自:衢州日报  本报讯 (记者 王继红 通讯员 叶超) 1月29日,位于智造新城...
伊朗首都启动战时避难设施建设规... 新华社德黑兰1月29日电(记者陈霄 沙达提)据伊朗媒体29日报道,伊朗首都德黑兰市政府已启动战时避难...