【问题标题】:Upload text as file with POST (multipart/form-data) using php and curl使用 php 和 curl 使用 POST (multipart/form-data) 将文本作为文件上传
【发布时间】:2009-05-22 12:04:09
【问题描述】:

我正在尝试实现的 API 需要上传包含命令的 XML 文件。 直接的方法是生成文件的内容,将其写入文件系统并使用 curl 上传到 Web 服务器。

我想要完成的是通过使用 php 的临时协议处理程序来跳过编写部分。示例代码如下:

<?php
  $fp = fopen("php://temp", "r+");

  $request = 'some xml here';
  fwrite($fp, $request);

  rewind($fp);

  $input_stat = fstat($fp);
  $size = $input_stat['size'];

  $url = "http://example.com/script.php";
  $ch = curl_init();

  $filename = $_POST[cert_file] ;
  $data['file'] = "@xml.xml";

  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST,1);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
  curl_setopt($ch,CURLOPT_INFILESIZE,$size);
  curl_setopt($ch,CURLOPT_INFILE,$fp);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  $result = curl_exec($ch);
  $error = curl_error($ch);

  echo 'result:'.$result."\n";
  echo 'error:'.$error."\n";

  curl_close($ch);
?>

不幸的是,这不起作用。 Tcpdump 显示没有发送请求。 更新:我得到的结果是:

结果:

错误:创建表单数据失败

有没有人知道如何使用 PHP 将文本作为文件即时上传?

【问题讨论】:

  • 您找到解决方案了吗?我有完全一样的问题。我正在尝试上传已经在缓冲区中的文件的内容。我也不想将其写回文件以便将其作为文件上传。
  • 我也有同样的问题 :(
  • 我仍然没有解决方案。

标签: php post file-upload curl


【解决方案1】:

在调用fwrite 之后,添加对rewind($fp) 的调用。在fwrite 之后,文件指针位于临时流的末尾。如果您致电rewind,它会将其重置为开头。下面是一个 PHP 会话的快速证明:

php > $fp = fopen("php://temp", "r+"); php > fputs($fp, "一些 xml\n"); php > echo stream_get_contents($fp); php > 倒带($fp); php > echo stream_get_contents($fp); 一些xml php > 退出

在第一次回显stream_get_contents 之后,没有任何回显。在rewind 之后,stream_get_contents 的第二个回显显示了 XML。

【讨论】:

    【解决方案2】:

    可能是因为在写入$fp 之后,文件句柄的指针指向文件末尾。你试过先倒带吗?

    fseek($fp, 0, SEEK_SET);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 2011-03-28
      • 2014-02-01
      相关资源
      最近更新 更多