dongxia8656 2011-05-21 10:30
浏览 80
已采纳

使用API​​ PUT请求上传文件

I'm building an API in PHP. One of the methods is place.new (PUT request). It expects several string fields, and it also expects an image. However I can't get it working. With a POST request it was easy, but I'm not sure how to do it with a PUT and how to get the data on the server.

thanks for the help!

Test CURL code

$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); 

Server code

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
        ...
    }
}

Solution

send

// 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); 

receive

/* 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条回答 默认 最新

  • dtnmuyoiw680512744 2011-05-21 10:44
    关注

    Did you read http://php.net/manual/en/features.file-upload.put-method.php ? Script PUT /put.php all set up?

    Also, what is $image -- it needs to be a file handler, not a file name.

    Ps. Using file_get_contents will try to load whatever is PUT on the server into memory. Not a good idea. See the linked manual page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因