【问题标题】:Sending raw binary and data with cURL使用 cURL 发送原始二进制文件和数据
【发布时间】:2016-02-02 16:36:12
【问题描述】:

我正在尝试使用 cURL 在 POST 中发送原始二进制文件以及其他一些数据。 基本上,我是这样做的:

//Here i create the CURLFile
$cfile = new CURLFile($fullpath,'application/xml', $filename); 

//Data to upload (including the file)
$data_upload = array('username' => $username, 
                     'password' => $password, 
                     'owner' => $owner, 
                     'destination' => $pathpda, 
                     'filename' => $filename, 
                     'filedata' => $cfile);
//Upload
$ch_upload = curl_init($urlws.$e_upload);
curl_setopt($ch_upload, CURLOPT_POST,true);
curl_setopt($ch_upload, CURLOPT_POSTFIELDS, $data_upload);
curl_setopt($ch_upload, CURLOPT_RETURNTRANSFER, true);
$response_upload = curl_exec($ch_upload);
curl_close($ch_upload); 

一切正常。除了现在我希望我的文件只是二进制数据而不是磁盘上的真实文件。另外,我需要在请求中发送其他数据! 有谁知道该怎么做?我在 Google 中查找,但我无法找到同时发送原始二进制文件和其他数据的方法。 谢谢!

更新 为了进一步澄清我的问题,我不需要只发送随机二进制数据,而是发送内容来自 ob_get_contents() 的文件(例如),因此它不是磁盘上的物理文件。如果我只是替换 CURLfile 以使用“filedata”变量发送二进制文件数据,它根本不起作用。 Web 服务无法识别该文件。也许有一种方法可以在不指向真实文件的情况下创建 CURLfile。

【问题讨论】:

  • 您的问题是如何发送不是光盘上真实文件的数据?
  • 我的问题是如何发送一个尚未保存在服务器磁盘上的文件,(例如,从数据库中检索的文件或 ob_get_contents() 的输出)与其他常用的发布数据一起使用卷曲。
  • 根据FILE这个词的定义,它存储在磁盘上的folder中,否则它只是内容。文件和文件系统只是数据存储方式的范例,您只想发送与发送用户名字符串没有什么不同的内容。
  • @BasvanStein - 你不知道你在说什么。

标签: php curl http-post binary-data raw-data


【解决方案1】:

与处理其他变量的方式完全相同。 最后,所有内容都以“二进制”形式发送,或者实际上以字符串表示形式发送。

就这样吧

$content = ob_get_contents();
//or file_get_contents() or whatever source
$data_upload = array('username' => $username, 
                 'password' => $password, 
                 'owner' => $owner, 
                 'destination' => $pathpda, 
                 'filename' => $filename, 
                 'filedata' => $cfile,
                 'allkindsofdata' => $content );

【讨论】:

  • 感谢您的回复,但它不起作用。我要发送的是一个文件,而不仅仅是二进制内容。 Web 服务不断回答“所需的请求部分 'filedata' 不存在”。我还尝试手动添加标题“Content-Type:multipart/form-data”并设置选项 CURLOPT_HEADER、CURLOPT_HTTPHEADER、CURLOPT_INFILESIZE 没有结果。在我的第一个实现中,我创建了一个 CURLfile。如果我可以使用 ob_get_contents() 的输出而不是引用磁盘上的真实文件来创建相同的 CURLfile,那就太好了。但我不认为可以这样做。
  • 但是您将什么定义为文件,您说内容可能来自文件但您不想将其作为文件发送对吗?所以基本上你尝试做的是将文件存储在变量中并发送它? (不是?),我建议你不要发送filename 和filedata,而只是将内容作为普通的 POST 变量发送。
  • 好吧,让它变得简单。我需要将$data_upload 变量中的数据发送到Web 服务。如果我将 CURLfile 替换为 ob_get_contents() 输出,则 Web 服务会以异常 400,"error":"Bad Request" "Required request part 'filedata' is not present." 进行回答。也许我需要向 curl_setopt 添加一个我不知道的选项。我需要帮助。不幸的是,您提出的解决方案不起作用。
【解决方案2】:

诀窍是让你的二进制字符串在内存中变成stream,然后告诉 curl 上传该流,使用:CURLOPT_INFILE、CURLOPT_INFILESIZE 和 CURLOPT_UPLOAD。 This answer 提供了执行此操作的代码。

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多