【问题标题】:Upload a file using an API PUT request使用 API PUT 请求上传文件
【发布时间】:2011-08-30 04:22:56
【问题描述】:

我正在用 PHP 构建一个 API。其中一种方法是 place.new(PUT 请求)。它需要几个字符串字段,并且还需要一个图像。但是我无法让它工作。使用 POST 请求很容易,但我不确定如何使用 PUT 以及如何在服务器上获取数据。

感谢您的帮助!

测试 CURL 代码

$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $this->url);

curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_INFILE, $image);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($image));

$this->result = curl_exec($curl);
curl_close($curl); 

服务器代码

if ( $im_s = file_get_contents('php://input') )
{
    $image = imagecreatefromstring($im_s);

    if ( $image != '' )
    {
        $filename = sha1($title.rand(11111, 99999)).'.jpg';
        $photo_url = $temp_dir . $filename;
        imagejpeg($image, $photo_url);

        // upload image
        ...
    }
}

解决方案

发送

// Correct: /Users/john/Sites/....
// Incorrect: http://localhost/...
$image = fopen($file_on_dir_not_url, "rb");

$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_INFILE, $image);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file_on_dir_not_url));

$result = curl_exec($curl);
curl_close($curl); 

接收

/* Added to clarify, per comments */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen($photo_url, "w");

/* Read the data 1 KB at a time
    and write to the file */
while ($data = fread($putdata, 1024))
{
    fwrite($fp, $data);
}

/* Close the streams */
fclose($fp);
fclose($putdata);

【问题讨论】:

  • 我认为接收部分缺少一些东西:$putdata = fopen("php://input", "r");

标签: php curl upload request put


【解决方案1】:

你读过http://php.net/manual/en/features.file-upload.put-method.php 吗? Script PUT /put.php全部设置好了吗?

另外,$image 是什么——它必须是文件处理程序,而不是文件名。

附言。使用file_get_contents 将尝试将服务器上的任何内容加载到内存中。不是一个好主意。请参阅链接的手册页。

【讨论】:

  • 谢谢!我之前没有到达那个在谷歌上搜索的页面。将这些信息与 SO 的一些答案结合起来,我得到了它的工作:)
  • 感谢发布工作解决方案,但接收代码错过了$putdata 的初始化。
猜你喜欢
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 2017-07-26
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多