使用curl请求php图像上传

使用curl请求php图像上传

问题描述:

我试图通过上传一个图像文件到服务器imageUploader.php。我需要从角度脚本和php脚本上传图片。我的角度http请求成功上传图像,但PHP脚本无法上传图像文件。使用curl请求php图像上传

这是角请求:

fd = new FormData(); 
fd.append('file', file); 

    $http 
    .post(uUrl, fd, { 
     transformRequest: angular.identity, 
     headers: { 
      'Content-Type': "multipart/form-data" 
     } 
    }) 

,这是PHP请求

$data['file'] = new CurlFile($data_string['tmp_name'], $data_string['type']); 

    if (! isset ($this->conType)) 
     $this->conType = 'multipart/form-data'; 
    $ch = curl_init ($this->baseUrl ); 
    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    curl_setopt ($ch, CURLOPT_POST, 1); 
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    $this->addHeader ('Content-Type', $this->conType); 
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $this->headerArray); 
    $result = curl_exec ($ch); 

    public function addHeader($k, $v) { 
     array_push ($this->headerArray, $k . ": " . $v); 
    } 

的事情是,如果删除的multipart/form-data的在PHP脚本部分,图像成功上传,但是当我在服务器中查看图像时,无法查看图像内容。这就像上传图像时图像已损坏。

试试这个代码,它会帮助你使用curl

$ch = curl_init(); 
//$data = array('name' => 'Foo', 'file' => '@/path/to/image.jpeg'); 
$data['file'] = new CurlFile($data_string['tmp_name'], $data_string['type']); 
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php'); 
curl_setopt($ch, CURLOPT_POST, 1); 
//CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0 
//So next line is required as of php >= 5.6.0 
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
curl_exec($ch); 
+0

到uploadfile它给的我这个错误**的@filename API文件上传的用法已过时。请改用CURLFile类** –