使用API PUT请求上传文件

21

我正在使用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);

1
我认为接收部分缺少了某些内容:$putdata = fopen("php://input", "r"); - Paolo
1个回答

11

你有读过 http://php.net/manual/zh/features.file-upload.put-method.php 吗?Script PUT /put.php 已经设置好了吗?

此外,$image 是什么 -- 它需要是文件处理器,而不是文件名。

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


谢谢!我之前在谷歌上没找到那个页面。将那些信息与一些来自SO的答案结合起来,我终于让它工作了 :) - fesja
1
感谢您发布了可行的解决方案,但是接收代码缺少对 $putdata 的初始化。 - chx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接