---
title: "python3使用request来post文件请求"
author: "xiaojingjing"
date: "2019-08-28T17:35:35Z"
tags: ["Python", "REQUEST", "post", "文件"]
categories: ["编程语言"]
slug: "python3-request-post"
draft: false
lastmod: "2019-08-28T17:35:35Z"
id: 2443917
url: "https://xiaojingjing.iteye.com/blog/2443917"
---

最近尝试使用request来发送上传文件的post请求，网上找了很多直接post文件的例子，借鉴发现这个方法行不通，于是尝试了另外一种方式：通过第三方包requests\_toolbelt讲文件转为数据流来发送请求，尝试成功。

 

第一类，单个文件，包含在消息体

```
# -*- coding: utf-8 -*-

import requests
#引入requests_toolbelt包，直接使用数据流来发送上传文件的post请求
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = "http://host/test/bTutorCircle/uploadFile"

m=MultipartEncoder(fields = {
    "account":"qatest@chaozhi1v1.com",
    "metaTag":"TOPIC_IMAGE",
    'file':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')

})

headers = {
    'Accept-Encoding': "gzip, deflate",
    'Content-Type': m.content_type,
    }

response = requests.request("POST", url, data=m, headers=headers)

print(response.text)
```

 

第二类，多个文件，参数复杂组合情况

```
# -*- coding: utf-8 -*-

import requests
#引入requests_toolbelt包，直接使用数据流来发送上传文件的post请求
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = "http://host/test/content/inserOrUpdate?token=11E5F02EC251CCBFDBAF0BEE3B23DF35"

m=MultipartEncoder(fields = {
    "trainContent":str({"title":"tet","introduction":"<p>test</p>","videoLinkType":1,"videoUrl":"","videoDurationM":"2","videoDurationS":0,"videoDuration":120}),
    "ppt":('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),
    'cover':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),
    'video':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')

})

headers = {
    'Accept-Encoding': "gzip, deflate",
    'Content-Type': m.content_type,
    }

response = requests.request("POST", url, data=m, headers=headers)

print(response.text)
```

 

附件文件支持多种文件，比如ppt,xls,jmx等等，把对应字符替换即可。