一、說明
本文主要簡述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 }