[PHP] CURL文件上传
一、说明
本文主要简述CURL进行文件上传的一般操作,基于TP5框架;
二、前端
代码如下,需要填入对应的上传地址还有修改接收的参数名字(这里是 file):
<form action="上传地址" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">上传</button> </form>
三、后端
下面是基于TP5的上传处理,通过CURL上传到另外一台服务器上。
1 <?php 2 namespace app\controller; 3 4 use think\Controller; 5 6 //文件上传类 7 class Upload extends Controller 8 { 9 protected $file_size = 20971520;//20M 10 protected $file_type = ["png", "jpg", "jpeg", "gif"]; 11 protected $ret = ['code'=>0, 'msg'=>'', 'data'=>[]]; 12 private $uploadUrl = "http://xxx.com";//上传地址 13 14 public function doit() 15 { 16 try{ 17 $verify = $file->validate(['size'=>$this->file_size,'ext'=>$this->file_type]); 18 if (!$verify) { 19 throw new \Exception('上传的文件大小超过20M, 或文件类型不正确'); 20 } 21 22 $ext = pathinfo($file->getInfo('name'))['extension']; 23 $tm = time(); 24 $mime = $file->getInfo('type'); 25 26 //表单请求参数 27 $postData = [ 28 'file' => new \CURLFile(realpath($file->getPathname()), $mime, $fileName.".{$ext}"), 29 ]; 30 31 $curlRes = $this->curlUploadFile($this->uploadUrl, $postData); 32 $res = json_decode($curlRes, true); 33 34 if($res['code'] == 200 && $res['data']['filePath'] != ""){ 35 $this->ret['code'] = 200; 36 $this->ret['msg'] = '文件上传成功'; 37 $this->ret['data'] = ['filePath' => $res['data']['filePath']]; 38 }else{ 39 throw new \Exception('上传文件失败: '.$res['msg'], 500); 40 } 41 }catch(\Exception $ex){ 42 //异常处理 43 $this->ret['code'] = 500; 44 $this->ret['msg'] = $ex->getMessage(); 45 } 46 return json($this->ret);//返回json 47 } 48 50 51 //CURL文件上传 52 private function curlUploadFile($url, $data) 53 { 54 $curl = curl_init(); 55 if (class_exists('\CURLFile')) { 56 curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); 57 //$data = array('file' => new \CURLFile(realpath($path)));//>=5.5 58 } else { 59 if (defined('CURLOPT_SAFE_UPLOAD')) { 60 curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); 61 } 62 //$data = array('file' => '@' . realpath($path));//<=5.5 63 } 64 curl_setopt($curl, CURLOPT_URL, $url); 65 curl_setopt($curl, CURLOPT_POST, 1 ); 66 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); 67 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 68 $result = curl_exec($curl); 69 $error = curl_error($curl); 70 71 curl_close($curl); 72 73 return $result; 74 } 75 }
生命不息,学习不止