标签:
项目中要使用restful上传文件到服务器,一直不能成功,后生成相关串后在postman中上传成功,利用这个工具生成php curl的代码,后逐步比对产生以下代码。
/**
* 上传文件
* @param unknown $filename
*/
function fileUpload($filename,$type)
{
$serviceName=‘imageup‘;
$contents = file_get_contents($filename);
//content boundary
$boundary = md5(time());
$postStr = "";
$postStr .="-----".$boundary."\r\n";
$postStr .="Content-Disposition: form-data; name=\"file\"; filename=\"".$filename."\"\r\n";
$postStr .="Content-Type: jpg\r\n\r\n";
$postStr .=$contents."\r\n";
$postStr .="-----".$boundary."--";
$timestamp=$this->getMillisecond();
$signstr=$this->sign(‘‘, $timestamp, $this->prikey);
$post_data=array("v"=>$this->ver,
"ts"=>$timestamp,
"sign"=>$signstr,
"user"=>$this->userSn
);
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$timeout = 30;
$postUrl = $this->url_province.$serviceName."/".$type."/" .‘?‘ . $post_data;
$ch = curl_init();
$boundary = md5(time());
curl_setopt_array($ch, array(
CURLOPT_URL => $postUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 300,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postStr,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---".$boundary,
),
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$boundary 的格式不能改变,“-----”、“\r\n"上面程序已经过测试
标签:
原文地址:http://www.cnblogs.com/xihong2014/p/5894294.html