遇到一个需求是要把前端的上传文件经过php拿到而后再上传给接口,由于不能浏览器不能跨域上传拿到返回值,因此只能用前端上传,而后php拿到文件再上传一次。以前在网上找到curl方式不能上传二进制文件流,失败了结,代码以下:php
上传函数: 前端
function curl_upload_file($url,$filename,$path,$type,$d){
if (class_exists('\CURLFile')) {
$data['file'] = new \CURLFile(realpath($path),$type,$filename);
} else {
$data['file'] = '@'.realpath($path).";type=“.$type.”;filename=".$filename;
}json
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curl);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return_data = curl_exec($ch);
curl_close($ch);
return $return_data;
}api
函数使用:跨域
$file = $_FILES['file'];浏览器
$data = $this->curl_upload_file($url, $file['name'], $file['tmp_name'], $file['type'],$request);app
失败了结。curl
以后又在网上找到了二进制文件流的方式来模拟上传,终于成功,特写上完整代码函数
public function batchUpload(){post
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('memory_limit', '128M');
$request = array();
$request['type'] = $req->getParameter('type','1');
$request['userToken'] = $this->userToken;
$request['apiKey'] = $this->apiKey;
$url ="http:www.test.com/comdata/importExcelSuit?";
$result = array();
$result['success'] = 1;
$allowtype = array("xlsx", "xls");
$file = $_FILES['file'];
$aryStr = explode(".", $file['name']);
$allowsize = 10485760;
if (!in_array(strtolower($aryStr[count($aryStr)-1]), $allowtype)) {
$result['success'] = -1;
$result['msg'] = "请上传excel文件!";
}
if ($file['error'] != 0) {
$result['success'] = -1;
$result['msg'] = '上传出错';
}
if ($file['size'] > $allowsize) {
$result['success'] = -1;
$result['msg'] = '请上传文件大小小于10M';
}
if($result['success']!=-1){
$fileurl = $url .'?'. http_build_query($request);
$data = base::sendStreamFile($fileurl,$file['tmp_name']);
$result['data'] = json_decode($data,true);
if($result['data']['statuscode'] != 1){
$result['success'] = -1;
$result['msg'] = $result['data']['dataInfo'];
}else{
$result['success'] = 1;
}
}
echo json_encode($result);
}
上传函数为
static function sendStreamFile($url,$file)
{
if (empty($url) || empty($file))
{
return false;
}
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'content-type:application/x-www-form-urlencoded',
'content' => $file
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return $response;
}
全部上传函数都是从网上down下来,感谢各位前辈的无私分享,由于来源比较杂,没法标明出处,我只是代码的搬运工。