简体   繁体   中英

upload image error with php class and curl

hi i have this code 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;
        }
    }

and i use like this:

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

but the problem is that wht uploads is the tmp_name as a file and not the image but if i change this line: $file = $_FILES['archivo']['tmp_name']; to $file = $_FILES['archivo']['name'];

i get this error: failed creating formpost data

my question is how to use the class orectly so i can upload the image

maybe you should specify headers to your image data try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM