php 使用 API PUT 请求上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6081131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload a file using an API PUT request
提问by fesja
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.
我正在用 PHP 构建 API。其中一种方法是 place.new(PUT 请求)。它需要几个字符串字段,还需要一个图像。但是我无法让它工作。使用 POST 请求很容易,但我不确定如何使用 PUT 执行此操作以及如何在服务器上获取数据。
thanks for the help!
谢谢您的帮助!
Test CURL code
测试 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);
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);
采纳答案by chx
Did you read http://php.net/manual/en/features.file-upload.put-method.php? Script PUT /put.php
all set up?
你读过http://php.net/manual/en/features.file-upload.put-method.php吗?Script PUT /put.php
都设置好了吗?
Also, what is $image
-- it needs to be a file handler, not a file name.
另外,什么是$image
- 它需要是文件处理程序,而不是文件名。
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.
附言。Usingfile_get_contents
将尝试将服务器上的任何内容加载到内存中。不是个好主意。请参阅链接的手册页。