gpt4 book ai didi

python - 如何使用 requests.put() 通过 Python 上传文件?

转载 作者:行者123 更新时间:2023-12-04 03:02:41 27 4
gpt4 key购买 nike

我正在尝试使用 Python 中的请求库将文件上传到本地主机上的 Fedora 公共(public)存储库。我很确定我的主要问题是不理解 open()/read()以及我需要做什么才能通过 http 请求发送数据。

def postBinary(fileName,dirPath,url):
path = dirPath+'/'+fileName
print('to ' + url + '\n' + path)
openBin = {'file':(fileName,open(path,'rb').read())}
headers = {'Slug': fileName} #not important
r = requests.put(url, files=openBin,headers=headers, auth=HTTPBasicAuth('username', 'pass'))
print(r.text)
print("and the url used:")
print(r.url)
这将成功上传存储库中的文件,但之后文件会稍大并损坏。例如,一个 6.6kb 的图像变成了 6.75kb 并且无法再打开。
那么我应该如何在 python 中使用 put 正确打开和上传文件呢?

###额外细节:###
  • 当我更换 files=openBindata=openBin我最终得到了我的字典,我假设数据是一个字符串。我不知道这些信息是否有用。
    “文件=FILE_NAME.extension&file=TYPE89a%24%02Q%03%E7%FF%00E%5B%19%FC%....
    并且文件的大小增加到几兆字节
  • 我使用的是专门 put 因为 Fedora RESTful HTTP API 端点说要使用 put .

  • 以下命令确实有效: curl -u username:password -H "Content-Type: text/plain" -X PUT -T /path/to/someFile.jpeg http://localhost:8080/fcrepo/rest/someFile.jpeg

    最佳答案

    更新
    使用 requests.put()files参数发送一个多部分/表单数据编码请求,即使声明了正确的内容类型,服务器似乎也无法在不破坏数据的情况下处理该请求。curl命令只需使用请求正文中包含的原始数据执行 PUT。您可以通过在 data 中传递文件数据来创建类似的请求。范围。在 header 中指定内容类型:

    headers = {'Content-type': 'image/jpeg', 'Slug': fileName}
    r = requests.put(url, data=open(path, 'rb'), headers=headers, auth=('username', 'pass'))
    您可以更改 Content-type header 以根据需要适应有效负载。

    尝试设置 Content-type为文件。
    如果您确定它是文本文件,请尝试 text/plain您在 curl 中使用的命令 - 即使您似乎正在上传 jpeg 文件?但是,对于 jpeg 图像,您应该使用 image/jpeg .
    否则,对于任意二进制数据,您可以使用 application/octet-stream :
    openBin = {'file': (fileName, open(path,'rb'), 'image/jpeg' )}
    此外,无需显式读取代码中的文件内容, requests将为您执行此操作,因此只需传递打开的文件句柄,如上所示。

    关于python - 如何使用 requests.put() 通过 Python 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47781633/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com