如何使用PHP,curl和HTTP POST通过流文件上传文件? [英] How to upload a file with PHP, curl and HTTP POST by streaming the file?

查看:1021
本文介绍了如何使用PHP,curl和HTTP POST通过流文件上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个大文件,我想使用PHP和curl的HTTP POST到webservice。该文件大于我可以让PHP使用的内存量。

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.

基本上,我正在寻找一种方式直接流文件的内容到curl,没有

Basically I'm looking for a way to stream the content of a file directly to curl, without reading the entire file into memory.

我已使用multipart POSTs和PUT成功,但不是使用POST的二进制数据上传。

I have success using multipart POSTs and PUT, but not "binary data" upload with POST.

我想在PHP中实现这个命令行:

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"

使用curl_setopt尝试了很多选项,例如INFILE,POSTFIELDS,Content-Type头,但没有运气。

Tried a lot of options with curl_setopt, such as INFILE, POSTFIELDS, Content-Type header, but no luck.

它适用于multipart虽然,但我需要一个原始的POST请求,没有multiparts:

It works with multipart though, but I need a raw POST request, no multiparts:

$post['file'] = "@large.jpg";
curl_setopt($c, CURLOPT_POSTFIELDS, $post);


推荐答案

PHP / CURL绑定支持CURLOPT_READFUNCTION选项

The PHP/CURL binding supports the CURLOPT_READFUNCTION option, which allows you to pass data to send chunk-by-chunk using that callback.

几乎完全相同的逻辑,如下面的C示例所示:
< a href =http://curl.haxx.se/libcurl/c/post-callback.html =nofollow> http://curl.haxx.se/libcurl/c/post-callback.html

Pretty much exactly the same logic as is shown in this C example: http://curl.haxx.se/libcurl/c/post-callback.html

这篇关于如何使用PHP,curl和HTTP POST通过流文件上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆