share-image
ESC

使用requests 库上传文件遇到的坑

在将文件上传到对象存储时,验证 token 都是成功的,但是上传的文件一直打不开,一开

始我是这样写的上传的:


url = requestaddress+'/'+bucketname+'/'+objectname

files = {'file': open(filepath,'rb')}

r = requests.post(url,params=querystring,headers=headers,files=files)

print(r.json())

但是上传后的文件一直打不开。抓包查看请求数据,发现会带有

--94642781300f420a8263e3833d1965cb..Content-Disposition: form-data; name="file"; filename="test.jpg"
8....jU'.h..d..4TnJ.........--94642781300f420a8263e3833d1965cb--..

这些数据


看了requests 的官网的文档说是强烈推荐使用二进制方式上传文件,因为

于是使用with open 打开文件后上传

with open(filepath, 'r') as f:

r = requests.post(url,params=querystring,headers=headers,data=f)

print(r.json())

结果发现可以

附上传代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

import base64
import hmac
import hashlib
import time
import requests
import json
import datetime


# 计算token


def token(accesskey,secretkey,bucketname,objectname):

expirestime = int(time.time()+6000)

json_data = {"Bucket":bucketname,"Object":objectname,"Expires":expirestime}

putpolicy = json.dumps(json_data)

encodedputpolicy = base64.b64encode(putpolicy)

signature = hmac.new(secretkey, encodedputpolicy, digestmod=hashlib.sha256).digest();

encodedsign = base64.b64encode(signature)

token = "UPLOAD " + accesskey + ":" + encodedsign + ":" + encodedputpolicy

return token

# 获取最佳节点

def getnode(bucketname):

url ='http://lbs-eastchina1.126.net/lbs?version=1.0'+'&bucketname='+bucketname

node = requests.get(url)

nodeValue= node.json()

return nodeValue['upload'][0]

# 分块上传

def postfile(xnostoken,bucketname,
objectname,offset,
complete,host,contentlength,
contenttype,filepath):
gmtformat = '%a, %d %b %Y %H:%M:%S GMT'
gmtdate = datetime.datetime.utcnow().strftime(gmtformat)
querystring = {"offset":offset,"complete":complete,"version":1.0}

headers = {'Host':host,'Content-Length':contentlength,
'x-nos-token':xnostoken,'Content-type':contenttype,'Date':gmtdate}

requestaddress = getnode(bucketname)

requestaddress = str(requestaddress)

url = requestaddress+'/'+bucketname+'/'+objectname

with open(filepath, 'r') as f:

requestapi = requests.post(url,params=querystring,headers=headers,data=f)

print(requestapi.json())

def main():

bucketname = 'netease01'

objectname = '3.jpg'

accesskey = ""

secretkey = ""

offset = 0

complete = True

host = 'nos-eastchina1.126.net'

contenttype = 'image/jpeg'

contentlength = '34771'

filepath = '/Users/wenjun/PycharmProjects/Test/test.jpg'

xnostoken = token(accesskey,secretkey,bucketname,objectname)

postfile(xnostoken,bucketname,objectname,offset,complete,host,contentlength,contenttype,filepath)


if __name__ == '__main__':

main()

文章作者:阿文
文章链接: https://www.awen.me/post/1168.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客
本文于 2018-01-25 发布,已超过半年(2926天),请注意甄别内容是否已过期。