遇到一个需求是要把前端的上传文件通过php拿到然后再上传给接口,因为不能浏览器不能跨域上传拿到返回值,所以只能用前端上传,然后php拿到文件再上传一次。之前在网上找到curl方式不能上传二进制文件流,失败告终,代码如下:
上传函数:
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; }$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; }函数使用:
$file = $_FILES['file'];
$data = $this->curl_upload_file($url, $file['name'], $file['tmp_name'], $file['type'],$request);
失败告终。
之后又在网上找到了二进制文件流的方式来模拟上传,终于成功,特写上完整代码
public function batchUpload(){
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下来,感谢各位前辈的无私分享,因为来源比较杂,无法标明出处,我只是代码的搬运工。