可以使用cURL通过POST方法进行流式上传文件吗?

12

还是说PHP不支持这个功能?我已经读过使用PUT方法可以实现,但服务器只接受POST方法。


我相信pecl_http在2.x分支中有能力做到那样的事情。 - Ja͢ck
1
请使用PHP中的CURL将文件字符串发布。重复问题,请参考https://dev59.com/MXA75IYBdhLWcg3w0sp9 - bwoebi
服务器需要接受这个内容类型为application/octet-stream。 - Ross Logan
3个回答

7
cURL已经支持流,尝试使用curl --help | grep binary命令,你将得到以下结果:

--data-binary DATA HTTP POST二进制数据 (H)

一个例子:

curl -v -XPOST http://example:port/path --data-binary @file.tar
-H "Content-Type: application/octet-stream"


6
@file会将内容加载到内存中。对于大文件来说不好。应该使用-T选项代替。 - Fred Simon

3

是的,使用cURL POST文件上传可以实现流式上传。这是默认设置,您需要以字符串形式提供要流式传输的文件的文件名。

// URL on which we have to post data
$url = "http://localhost/tutorials/post_action.php";
// Any other field you might want to catch
$post_data['name'] = "khan";
// File you want to upload/post
$post_data['file'] = "@c:/logs.log";

// Initialize cURL
$ch = curl_init();
// Set URL on which you want to post the Form and/or data
curl_setopt($ch, CURLOPT_URL, $url);
// Data+Files to be posted
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Pass TRUE or 1 if you want to wait for and catch the response against the request made
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// For Debug mode; shows up any error encountered during the operation
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Execute the request
$response = curl_exec($ch);

// Just for debug: to see response
echo $response;

除了默认方法之外,使用cURL无法使用POST方法来流式上传文件。

0

上传二进制文件的命令

curl --location --request POST 'http://localhost:8080/hello/read' \
-H "Content-Type: application/octet-stream" \
--data-binary '@/Users/krishna/Documents/demo.bin'

上传文本文件的命令

curl --location --request POST 'http://localhost:8080/hello/read' \
--header 'Content-Type: text/plain' \
--data-binary '@/Users/krishna/Documents/demo.txt'

根据文件内容设置Content-Type。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接