PHP POST Rest Service,保存通过$_FILES发送的图像


PHP POST Rest Service, save image sent via $_FILES

我做了一个REST服务,它主要基于本教程。我还制作了一个 REST 请求库,它主要基于本教程。(基本上,一堆关于$_SERVER['REQUEST_METHOD'] switch)。API 还使用 cURL 发出请求。

protected function executePost ($ch)
{
    if (!is_string($this->requestBody))  
    {  
        $this->buildPostBody();  
    }  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);  
    curl_setopt($ch, CURLOPT_POST, 1);  
    $this->doExecute($ch); 
}
protected function doExecute (&$curlHandle)
{
    $this->setCurlOpts($curlHandle);  
    $this->responseBody = curl_exec($curlHandle);  
    $this->responseInfo = curl_getinfo($curlHandle);  
    curl_close($curlHandle);  
}

我有 2 个简单的 HTML 表单,一个带有 get 方法,一个用于 post 方法。当我使用其中一个与简单的输入文本时,工作正常。我在服务中获取/返回值没有问题。

但是我需要从 HTML 表单发送图像,在我的服务中接收它,然后将其保存在服务器上。

这是我午餐对服务进行查询的部分。

print_r($_FILES);
//move_uploaded_file( $_FILES["image1"]["tmp_name"], "Images/" . $_FILES["image1"]["name"] ); when uncommented, This line actually works and save the image in my folder.
include("RestUtils.php");
$request = new RestRequestOperator('http://localhost:8080/REST/RestControler.php/user/1', 'POST', $_FILES);  
$request->execute();  

在我的服务中,我收到图像信息,即tmp_name和名称。当我尝试使用 move_uploaded_file( 和正确的参数保存图像时,它不起作用。

我意识到在tmp文件夹中保存"短圈时间"的图像文件有某种魔力。 当我调用我的服务时,图像已被删除?

总结 :我想知道是否可以将图像发送到 PHP REST API 并将其保存在他们的服务器上。

编辑:我在服务中添加了。

if(file_exists($_POST["image1"]["tmp_name"] )){
     echo "file EXISTS<br>";
}else echo "NOPE.<br>";
if(is_uploaded_file($_POST["image1"]["tmp_name"] )){
     echo "is_uploaded_file TRUE<br>";
}else echo "is_uploaded_file FALSE<br> .";
if(move_uploaded_file( $_POST["image1"]["tmp_name"], "Images/" .$_POST["image1"]["name"] )){
     echo "move_uploaded_file SUCCESS ";
}else echo "NOT move_uploaded_file";

输出:文件存在,is_uploaded_file假,不move_uploaded_file这意味着该文件实际上仍然存在于服务中,但上传的文件返回 false,可能是因为我在服务中使用 POST 数组而不是 $_FILES 数组,它在我的服务中是空的......

找到了,适用于本地 wamp PHP 5.3.4 !

public static function processRequest()
{
    case 'post':
       if(move_uploaded_file($_FILES["uploaded_file"]["tmp_name"] , "Images/" . $_FILES["uploaded_file"]["name"] )){
                    echo "move_uploaded_file SUCCESS ";
    ......................................                
}
......................................           
protected function executePost ($ch)
{
    $tmpfile = $_FILES['image1']['tmp_name'];
    $filename = basename($_FILES['image1']['name']);
    $data = array(
        'uploaded_file' => '@' . $tmpfile . ';filename='.$filename,
    );
    curl_setopt($ch, CURLOPT_POST, 1);             
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    //no need httpheaders
    $this->doExecute($ch); 
}

谢谢。戴夫

检查 POST 的编码类型。在表单中,它必须是"多部分/表单数据",所以我假设您的 POST REST 调用需要具有类似的编码类型才能使文件上传正常工作。