码迷,mamicode.com
首页 > Web开发 > 详细

requests上传文件

时间:2018-07-20 13:51:29      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:bytesio   params   ams   http   www   import   filename   href   file   

"""
requests上传文件时,如果文件名是中文,会导致上传失败,参考:https://www.cnblogs.com/liaofeifight/p/5807901.html

"""

# 不修改源码解决方式如下:
from django.conf import settings
import requests
import urllib
from urllib import parse
import json
import logging
import os
from io import BytesIO


 params = {
            "t": 4
        }
        data_bin = BytesIO(fileobj.read())

        # encode_data = encode_multipart_formdata(fileobj.read())
        # data = encode_data[0]
        ext = os.path.splitext(fileobj.name.rstrip())[1].lower().split(‘.‘)[-1]
        # files = {"file": (fileobj.name, fileobj.read(), ‘image/%s‘ % ext)}
        # ("filename", "fileobject", "content-type", "headers")
        name = parse.quote(filename.encode(‘utf-8‘))
        files = {"file":  (name, data_bin, ‘image/%s‘ % ext)}
        
        try:
            # wb_data = requests.post(url, data=json.dumps(params), headers=self.headers)
            wb_data = requests.post(url, data=params, files=files)
            data_bin.close()
            # print(wb_data.content)
            wb_data = json.loads(wb_data.content.decode(‘utf-8‘))

            if wb_data[‘code‘] == 0:
                # print(wb_data[‘path‘])

requests上传文件

标签:bytesio   params   ams   http   www   import   filename   href   file   

原文地址:https://www.cnblogs.com/lajiao/p/9340851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!