如何修复 PyCurl 命令未将 JSON 文件上传到服务器

How to fix PyCurl command not uploading JSON file to server

我正在尝试将 JSON 文件上传到服务器以用于测试。我试过这段代码,它给出了正确的状态输出,但文件没有上传到服务器:

import pycurl
import sys

mosaic_path = sys.argv[1]

file = open(mosaic_path)
print(mosaic_path)

c = pycurl.Curl()
c.setopt(c.URL, 'http://test-URL:21308/mosaic/testing/')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
c.setopt(c.PUT, 1)
c.setopt(c.READDATA, file)
c.perform()
print('Status: %d' % c.getinfo(c.RESPONSE_CODE))
c.close()
file.close()

这个 cURL 命令确实有效:

curl -I -T 2by2_hero_2by2.json http://test-URL:21308/mosaic/testing

(我正在尝试将这些 curl 命令更新为 python 个脚本)

如有任何帮助,我们将不胜感激。

你可以参考这个问题:Uploading a file via pyCurl

您这样做的方式会使 http 请求 header 如下所示:

PUT /mosaic/testing/ HTTP/1.1
Host: test-URL:21308
Content-Type: application/json
Accept: application/json

<the content of mosaic_path>

服务器不会将这样的 header 视为有效的文件传输信号,因为通过 http 传输文件的唯一方法是使用 Content-Type: multipart/form-data 并重构发送文件的方式内容(使用边界)。参考这个问题:How does HTTP file upload work?