使用php类和curl上传图像错误

时间:2014-11-11 06:44:50

标签: php

嗨,我有这个代码uploader.php:

class Uploader 
    {
        var $filePath;
        var $uploadURL;
        var $formFileVariableName;
        var $postParams = array ();

        function Uploader($filePath, $uploadURL, $formFileVariableName, $otherParams = false) 
        {
            $this->filePath = $filePath;
            $this->uploadURL = $uploadURL;
            if(is_array($otherParams) && $otherParams != false) 
            {
                foreach($otherParams as $fieldName => $fieldValue) 
                {
                    $this->postParams[$fieldName] = $fieldValue;
                }
            }
            $this->postParams[$formFileVariableName] = "@" . $filePath;
        }

        function UploadFile() 
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->uploadURL);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postParams);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $postResult = curl_exec($ch);

            if (curl_errno($ch)) 
            {
                print curl_error($ch);
                print "Unable to upload file.";
                exit();
            }
            curl_close($ch);

            return $postResult;
        }
    }

我喜欢这样:

require('uploader.php');

$upload_server = "http://developers.mytech.com.mx/files/api/upload.php";
     $file = $_FILES['archivo']['tmp_name'];
$archivo = $file;
$extension = pathinfo($archivo, PATHINFO_EXTENSION);
$nombre_base = basename($archivo, '.'.$extension);
    $upload = new Uploader($file, $upload_server,'file', array('api_key' => 'ic00n6yokd'));
    $result = $upload->UploadFile();
    if(preg_match("/upload_failed/", $result)){ echo "Upload failed."; }
    if(preg_match("/error_tamano/", $result)){ echo "Archivo muy grande."; }
    if(preg_match("/api_invalida/", $result)){ echo "Invalid API Code."; }
    if(preg_match("/error_type/", $result)){ echo "Archivo no valido."; }
    if(preg_match("/upload_success/", $result)){ echo $result; }

但问题是上传的是tmp_name作为文件而不是图像 但如果我改变这一行:$ file = $ _FILES ['archivo'] ['tmp_name']; to $ file = $ _FILES ['archivo'] ['name'];

我收到此错误:创建formpost数据失败

我的问题是如何使用该类,所以我可以上传图像

1 个答案:

答案 0 :(得分:0)

也许您应该为图像数据指定标题 试试这个:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'content-type: image/png'
 ));