//引入 use think\Image; /* * $name為表單上傳的name值 * $filePath為為保存在入口文件夾public下面uploads/下面的文件夾名稱,沒有的話會自動創建 * $width指定縮略寬度 * $height指定縮略高度 * 自動生成的縮略圖保存在$filePath文件夾下面的thumb文件夾里,自動創建 * @return array 一個是圖片路徑,一個是縮略圖路徑,如下: * array(2) { ["filepath"] => string(57) "uploads/img/20171211\3d4ca4098a8fb0f90e5f53fd7cd71535.jpg" ["thumbimgpath"] => string(63) "uploads/img/thumb/20171211/3d4ca4098a8fb0f90e5f53fd7cd71535.jpg" } */ protected function uploadFile($name,$filePath,$width = 0,$height = 0) { $file = request()->file($name); if($file){ $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filePath; if (!file_exists($filePaths)) { mkdir($filePaths, 0777, true); } $info = $file->move($filePaths); if ($info) { $imgpath = $filePaths . '/' . $info->getSaveName(); $url_path = '/uploads/'. $filePath . '/' . $info->getSaveName(); $image = \think\Image::open($imgpath); $date_path = $filePaths . '/thumb/' . date('Ymd'); $thumb_url = '/uploads/'. $filePath .'/thumb/' . date('Ymd'); if (!file_exists($date_path)) { mkdir($date_path, 0777, true); } $thumb_path = $date_path . '/' . $info->getFilename(); $thumb_url_path = $thumb_url . '/' . $info->getFilename(); $image->thumb($width, $height)->save($thumb_path); $uploadinfo = ['code' => 0, 'data' => ['filepath' => $url_path,'thumbimgpath'=>$thumb_url_path],'msg'=>'']; return json_encode($uploadinfo); }else{ // 上傳失敗獲取錯誤信息 return json_encode(['code'=>-1,'data'=>'','msg'=>$file->getError()]); } } } //調用 www.xxx.com/api/goods/uploadFile $res = uploadFile('image','goods',200,200); var_dump($res);