public function genUploadHeaderAndBody($pathInfo, $getParams, $postParams, $filePath, $uploadNameField = 'file') {
if (!file_exists($filePath) || empty(filesize($filePath))) {
return false;
}
$delimiter = '------------------' . uniqid();
$body = self::genPostBody($delimiter, $postParams, $filePath, $uploadNameField);
$header = array(
'pathinfo' => $pathInfo,
'querystring' => http_build_query($getParams),
'Content-Type' => 'multipart/form-data; boundary=' . $delimiter,
'Content-Length' => strlen($body),
);
return array(
'header' => $header,
'body' => $body,
);
}
private function genPostBody($delimiter, $postParams, $filePath, $uploadNameField) {
$fp = fopen($filePath, 'r');
$fileContent = fread($fp, filesize($filePath));
fclose($fp);
$data = '';
$eol = "\r\n";
// 拼接post参数
foreach ($postParams as $key => $value) {
$data .= '--' . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n";
$data .= $value . "\r\n";
}
// 拼接文件流
$data .= '--' . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $uploadNameField . '"; filename="' . basename($filePath) . "\"\r\n";
$data .= 'Content-Type: application/octet-stream' . "\r\n\r\n";
$data .= $fileContent . "\r\n";
$data .= '--' . $delimiter . '--' . "\r\n";
return $data;
}
public function execute(){
$pathInfo = '/filecenter/file/upload/';
$getParams = array(
'tpl' => 6,
'cuid' => 'activitycuid',
);
$filePath = '/home/zbl/data/z1.jpg';
$postParams = array(
'is_public' => 1,
'extension' => 'jpg',
'mcs_channel' => 'thumbnail',
'md5' => md5_file($filePath),
);
$getParams['sign'] = 'xxxxxxx';
$req = self::genUploadHeaderAndBody($pathInfo, $getParams, $postParams, $filePath, 'file');
if (!$req) {
echo "error on genUploadHeaderAndBody";
return;
}
$rst = curl('MobileToolsService', 'post', $req['body'], '', $req['header']);
if ($rst) {
echo $rst;
}
else {
var_dump($rst);
}
}
网友评论