如何使用 PHP、curl 和 HTTP POST 通过流式传输文件来上传文件?
假设我有一个大文件,我想使用 PHP 和curl 通过 HTTP POST 到 Web 服务。该文件大于我可以让 PHP 使用的内存量。
基本上我正在寻找一种方法将文件的内容直接流式传输到curl,而不将整个文件读入内存。
我成功地使用了多部分 POST 和 PUT,但没有使用 POST 上传“二进制数据”。
我想在 PHP 中实现的就是这个命令行的作用:
$ curl -X POST -H "Content-Type: image/jpeg" \
--data-binary "@large.jpg" "http://example.com/myservice"
使用curl_setopt尝试了很多选项,例如 INFILE、POSTFIELDS、Content-Type header,但没有运气。
虽然它适用于多部分,但我需要一个原始的 POST 请求,没有多部分:
$post['file'] = "@large.jpg";
curl_setopt($c, CURLOPT_POSTFIELDS, $post);
Lets say I have a large file that I want to HTTP POST to a webservice using PHP and curl. The file is larger than the amount of memory I can let PHP use.
Basically I'm looking for a way to stream the content of a file directly to curl, without reading the entire file into memory.
I have success using multipart POSTs and PUT, but not "binary data" upload with POST.
What I want to achieve in PHP is what this command line does:
$ curl -X POST -H "Content-Type: image/jpeg" \
--data-binary "@large.jpg" "http://example.com/myservice"
Tried a lot of options with curl_setopt, such as INFILE, POSTFIELDS, Content-Type header, but no luck.
It works with multipart though, but I need a raw POST request, no multiparts:
$post['file'] = "@large.jpg";
curl_setopt($c, CURLOPT_POSTFIELDS, $post);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP/CURL 绑定支持 CURLOPT_READFUNCTION 选项,该选项允许您使用该回调传递数据以逐块发送。
与此 C 示例中所示的逻辑几乎完全相同:
http://curl.haxx.se/libcurl/c/post-callback.html
The PHP/CURL binding supports the CURLOPT_READFUNCTION option, which allows you to pass data to send chunk-by-chunk using that callback.
Pretty much exactly the same logic as is shown in this C example:
http://curl.haxx.se/libcurl/c/post-callback.html