Python3: requests实现文件上传(对应postman form-data)。

python的requests实现文件上传,脚本如下【将url、header、data、filename、filepath替换成对应的即可】:

from urllib3 import encode_multipart_formdata
import requests
 
def post_files(filename, filepath):
    """
        :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    """
    url =  "........"
    # 第一种方法:
    with open(filepath,'rb') as f:
    	file = {"file" : ("filename", f.read())}
    	encode_data = encode_multipart_formdata(file)
    	file_data = encode_data[0]
    	header = {'Content-Type' : encode_data[1], .......(有内容可以再加key:value)}    # 'Content-Type': 'multipart/form-data; boundary=c0c46a5929c2ce4c935c9cff85bf11d4'
    	  res = requests.post(url, headers=header, data=file_data).json()
    print(res)
    # 第二种方法:
    file_data = {'file' =  (filename,open(filepath,'rb').read()}
    encode_data = encode_multipart_formdata(file_data)   
    data = encode_data[0]   # b'--c0c46a5929c2ce4c935c9cff85bf11d4\r\nContent-Disposition: form-data; name="file"; filename="1.txt"\r\nContent-Type: text/plain\r\n\r\n...........--c0c46a5929c2ce4c935c9cff85bf11d4--\r\n
    header = {'Content-Type' : encode_data[1], .......(有内容可以再加key:value)}    # 'Content-Type': 'multipart/form-data; boundary=c0c46a5929c2ce4c935c9cff85bf11d4'
    res = requests.post(url, headers=header, data=data).json()
    print(res)
 # 其实两种方法只不过打开文件的方式不一样
if __name__=="__main__":
    #url,filename,filepath string
    #header,data dict
    post_files("filename","filepath")


原文:https://blog.csdn.net/u013511989/article/details/80422734

猜你喜欢

转载自blog.csdn.net/xy_best_/article/details/84573087