requests.put上传文件Content-Disposition被写进了文件里

用requests.put上传文件

files = {'file':open(filepath,'rb').read()}
rs = requests.put(url=url, headers=headers,files=files)

上传成功后,打开上传成功的文件,发现请求头被写进了文件

--7deceadf843ce58e38485caec636a5bc
Content-Disposition: form-data; name="file"; filename="hmy.txt"

huangmanyao
--7deceadf843ce58e38485caec636a5bc--

解决方案

rs = requests.put(url=url,headers=headers,data=open(filepath,'rb'))

 

使用requests.put()files参数发送一个多部分/表单数据编码的请求,即使声明了正确的内容类型,服务器似乎也无法在不损坏数据的情况下处理该请求。

curl命令只是使用请求主体中包含的原始数据执行PUT。您可以通过在data参数中传递文件数据来创建类似的请求。指定标题中的内容类型:

headers = headers = {'Content-type': 'image/jpeg', 'Slug': fileName}
r = requests.put(url, data=open(path, 'rb'), headers=headers, auth=('username', 'pass'))

您可以根据需要改变Content-type头以适应负载。

尝试为文件设置Content-type

如果您确定它是一个文本文件,那么请尝试text/plain您在curl命令中使用的text/plain,即使您似乎正在上载一个jpeg文件?但是,对于jpeg图像,应该使用image/jpeg

否则,对于任意二进制数据,可以使用application/octet-stream

openBin = {'file': (fileName, open(path,'rb'), 'image/jpeg' )}

另外,不需要显式地读取代码中的文件内容,requests将为您执行此操作,因此只需传递上面所示的打开文件句柄。

 

参考资料:https://www.cnpython.com/qa/92618

 

posted @ 2020-09-23 11:38  醒日是归时  阅读(1550)  评论(0编辑  收藏  举报