使用 HTTP PUT 方法测试文件上传

Posted

技术标签:

【中文标题】使用 HTTP PUT 方法测试文件上传【英文标题】:Test file upload using HTTP PUT method 【发布时间】:2011-07-05 20:39:34 【问题描述】:

我编写了一个使用 HTTP PUT 方法上传文件的服务。

Web 浏览器不支持 PUT,所以我需要一种测试方法。它非常适合作为 POST 从浏览器点击它。

更新:这是有效的。我试过海报,但它与使用提琴手有同样的问题。您必须知道如何构建请求。 curl 解决了这个问题。

curl -X PUT "localhost:8080/urlstuffhere" -F "file=@filename" -b "JSESSIONID=cookievalue"

【问题讨论】:

【参考方案1】:

如果您使用的是 php,您可以使用以下代码测试您的 PUT 上传:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

【讨论】:

【参考方案2】:

在我看来,进行此类测试的最佳工具是 curl。它的--upload-file 选项通过PUT 上传文件,这正是您想要的(它可以做更多事情,比如修改HTTP 标头,以防您需要):

curl http://myservice --upload-file file.txt

【讨论】:

@user381091 取决于您的平台,但似乎支持很多。这里是curl官网下载向导的链接:curl.haxx.se/dlwiz/?type=bin 请注意,curl 的 --data 选项最初由该答案使用,不适合文件上传,因为它会去除换行符,因此可能会修改文件。我已将其替换为 --upload-file【参考方案3】:
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

【讨论】:

虽然这段代码可以解决问题,但最好补充说明一下,并为可能不理解这段代码的人解释它是如何工作的。 -X PUT 在使用-T--upload-file 的缩写)时是多余的。这与接受的答案基本相同(几年前)。【参考方案4】:

对于curl,使用-d 开关怎么样?喜欢:curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

【讨论】:

-d(或 --data)不适用于通用数据上传。请参阅文档。

以上是关于使用 HTTP PUT 方法测试文件上传的主要内容,如果未能解决你的问题,请参考以下文章

使用 API PUT 请求上传文件

使用 HTTP PUT 将文件上传到 Amazon S3

使用 HTTP PUT 将文件上传到 Sharepoint (WSS 3.0) 文档库

如何使用 REST API 中的 PUT 方法上传文件?

在 POSTMAN 上使用 PUT/POST 方法上传文件

Laravel 5.8 文件上传使用 PUT 方法和 ajax