程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

requests模块实现postman中form-data上传文件的方式(超大文件不适用)

发布于2019-08-17 20:45     阅读(4702)     评论(0)     点赞(2)     收藏(5)


postman上传文件方法:
在这里插入图片描述
只需在body中添加form-data
参数类型选择“file” or “text”
选择file就能轻松上传文件
而我们要用代码读出文件,并且实现这样的流式上传怎么办?
话不多说,直接上代码:

import requests
from urllib3 import encode_multipart_formdata

def post_file(url, file_path, file_name=None):
	"""
	:param url: 上传的服务器地址
	:param file_path: 文件路径
	:param file_name: 文件名称(上传到服务端文件即为这个名称, 不管原文件名称)
	:return: 服务器返回的内容
	"""
	# 读取文件内容
	file = open(file_path, "rb")
	file_content = file.read()
	file.close()
	# 准备请求体
	data = dict()
	
	# 处理文件名字
	if not file_name:
		file_name_list = file_path.rsplit("/", 1)  # 加入未给文件重新命名,使用文件原名称
		file_name = file_name_list[1]
	data['file'] = (file_name, file_content)
	encode_data = encode_multipart_formdata(data)
	data = encode_data[0]
    headers['Content-Type'] = encode_data[1]
    # 发送post请求
    try:
   		response = requests.post(url=url, headers=headers, data=data)
	except Exception as e:
   		pass
    return response

if __name__ == "__main__":
	response = post_file(url, file_path, file_name)
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34

关键代码:

encode_data = encode_multipart_formdata(data)
data = encode_data[0]
headers['Content-Type'] = encode_data[1]
  • 1
  • 2
  • 3

完。



所属网站分类: 技术文章 > 博客

作者:378273283782232

链接:https://www.pythonheidong.com/blog/article/48430/9f5d2ef1518da7306d15/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)