如何使用 requests.put() 来使用 Python 上传文件?

How do I use requests.put() to upload a file using Python?

我正在尝试使用 Python 中的请求库将文件上传到本地主机上的 Fedora 公共资源库。我相当确定我的主要问题是不理解 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)

这将在存储库中成功上传 a 文件,但之后它会稍大且损坏。例如,一个 6.6kb 的图像变成了 6.75kb 并且无法再打开。

那么我应该如何使用 put in python 正确打开和上传文件?

###额外的细节:###

以下命令有效:

curl -u username:password -H "Content-Type: text/plain" -X PUT -T /path/to/someFile.jpeg http://localhost:8080/fcrepo/rest/someFile.jpeg

已更新

使用带有 files 参数的 requests.put() 发送一个 multipart/form-data 编码的请求,服务器似乎无法在不破坏数据的情况下处理该请求,即使内容类型正确已宣布。

curl 命令仅使用请求的 body 中包含的原始数据执行 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 会为您完成,因此只需传递打开的文件句柄,如上所示。