确保在php.ini中打开了curl扩展。
本地服务器(文件上传端)代码:
/**
* 文件上传
*/
public function upload(){
$result=array('code'=>'','msg'=>'');
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('memory_limit', '128M');
$url="http://xx.xx.xx/api/upload"; //远程接口地址
$file = $_FILES['file'];
if ($file['error'] 0= 0) {
$filename = $file['name'];
$tmpfile = $file['tmp_name'];
$filetype = $file['type'];
//以下2种调用本类内部方法的方法任选其一
// $data = self::upload_file($url, $filename, $tmpfile, $filetype);
$data = $this->upload_file($url, $filename, $tmpfile, $filetype);
$dataarr = json_decode($data,true);
} else {
$result['code'] = 1;
$result['message'] = '上传出错';
}
$json= json_encode($result); //将数组转换成json对象
echo $json;
}
/**
* curl上传文件
*
* @param unknown $url
* @param unknown $filename
* @param unknown $path
* @param unknown $type
*/
private function upload_file($url,$filename,$path,$type){
//php 5.5以上的用法
if (class_exists('\CURLFile')) { //CURLFile是系统内部预定义类,前面加上反斜杠表示顶级命名空间,无论是调用CURLFile还是用class_exists()判断CURLFile的存在性,都推荐写成\CURLFile明确指定顶层空间,防止代码包裹在命名空间内的时候崩掉
$data = array('file' => new \CURLFile(realpath($path),$type,$filename));
} else {
//php 5.2以下的用法
$data = array(
'file'=>'@'.realpath($path).";type=".$type.";filename=".$filename
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
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;
}
远程服务器(文件接收端)代码:
function actionUpload(){
if( $_FILES){
$filename = $_FILES['file']['name'];
$tmpname = $_FILES['file']['tmp_name'];
$path = "/image/".date("YmdHis").mt_rand(1000,9999).substr($filename, strrpos($filename,'.'));
if(move_uploaded_file($tmpname, $_SERVER['DOCUMENT_ROOT'].$path)){
echo json_encode(["code"=>0,"msg"=>'上传成功',"url"=>$path]);
}else{
echo json_encode(["code"=>1,"msg"=>'上传失败',"url"=>null]);
}
}
}