zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    <转>修正版 疯狂代码 写给WEB2.0的站长
    一组MSSQL千万数量级分页存储过程
    flash AS +xml 加载图片(使用MovieClipLoader实现LOADING)
    [转]优化SQL Server的内存占用之执行缓存
    日志记录组件[Log4net]详细介绍(转)
    IBatis.Net如何支持多个数据库 [转帖]
    c#导入导出EXCEL
    弄了个新blogs 欢迎捧场
    ActionSrcipt 资源
    一个鼠标拖出一个圆形的简单demo
  • 原文地址:https://www.cnblogs.com/cherylgi/p/13717206.html
Copyright © 2011-2022 走看看