標籤:
圖片伺服器接的是搜狐雲台。在搜狐雲台上有程式碼封裝,下載下來,放到yii架構的vendor下。
yii2.0匯入第三方庫,很簡單,寫個autoload的檔案,然後在入口指令碼index.php中包含那個autoload檔案就好了。具體到這個雲台的庫,只要包含代碼中的autoload檔案就好了。
簡單介紹下搜狐雲台的實現,使用者會有一個對應的網域名稱,然後選擇建一些bucket,檔案的上傳下載都是在這個bucket中執行。函數調用在雲台提供的文檔中介紹的很清楚。這裡就不再介紹了。同時我只從php的部分來介紹,不考慮前端部分。
控制器部分
class SiteController extends Controller{ public function actionUpload(){ //return ImgUpdate::uploadToScs($_FILES); return ImgUpdate::uploadToLocal($_FILES); }}View Code
下面是封裝了一個圖片上傳的service。
<?php/** * Created by PhpStorm. * User: changshuiwang * Date: 2016/8/2 * Time: 17:51 */namespace common\service;use yii;use SohuCS\Scs\ScsClient;use yii\base\Exception;use yii\web\UploadedFile;class ImgUpdate{ const SCS_ACCESS_KEY=‘xxxxxxx‘; const SCS_SECRET_KEY=‘xxxxxxx‘; const HOST=‘xxxxxx‘; public static $type=array( ‘image/jpeg‘,‘image/png‘,‘image/jpg‘ ); public static $ext=array( ‘jpeg‘,‘png‘,‘jpg‘ ); /** * @param $file * @return string 返回一個json響應 */ public static function uploadToScs($file,$bucket=‘focus-img‘) { try{ $filename=$file[‘file‘][‘name‘]; $tmp_name=$file[‘file‘][‘tmp_name‘]; //檢查檔案合法 self::checkImgExt($filename,$tmp_name); if($file[‘file‘]){ $ext=self::getExtension($filename); $client = ScsClient::factory(array( ‘key‘ => self::SCS_ACCESS_KEY, ‘secret‘ => self::SCS_SECRET_KEY, ‘region‘ => "bjcnc" )); //判斷bucket是否存在 if(!$client->doesBucketExist($bucket)){ $result = $client->createBucket(array( ‘Bucket‘ => $bucket, ‘LocationConstraint‘ => self::HOST )); $client->waitUntilBucketExists(array(‘Bucket‘ => $bucket)); } $randName=uniqid().‘.‘.$ext; $filename="dianping/photos/".date(‘Ym‘,time())."/".$randName;//上傳之後的檔案名稱 $pathToFile=$tmp_name;//圖片上傳之後php產生的臨時檔案名稱 $result = $client->putObject(array( ‘Bucket‘ => $bucket, ‘Key‘ => $filename, ‘Body‘ => fopen($pathToFile,‘r+‘), )); return json_encode(array( ‘status‘=>‘success‘, ‘msg‘=>self::HOST.‘/‘.$bucket.‘/‘.$filename, )); }else{ throw new Exception("圖片不可為空"); } }catch(Exception $e){ return json_encode(array( ‘status‘=>‘error‘, ‘msg‘=>$e->getMessage(), )); } } /** * @param $file 上傳的圖片 $_FILES * @return string 返回json串 */ public static function uploadToLocal($file) { try{ $image=UploadedFile::usrLoadFiles();//擷取到圖片上傳類 if($image){ //檢查檔案合法 $filename=$file[‘file‘][‘name‘]; $tmp_name=$file[‘file‘][‘tmp_name‘]; self::checkImgExt($filename,$tmp_name); //將圖片移動到指定目錄下 $image=$image[‘file‘]; $ext = $image->getExtension(); $randName = uniqid() . "." . $ext; $path = date(‘y-m-d‘,time()); $rootPath = ‘uploads/‘ . $path . "/"; //檔案上傳路徑,使用的是相對路徑,如果以/開頭,linux上會從系統根目錄而不是web根目錄 if (!file_exists($rootPath)) { mkdir($rootPath,0777); } $image->saveAs($rootPath . $randName); $photo = ‘/‘.$rootPath.$randName;//圖片存放到資料庫的路徑 return json_encode(array( ‘status‘=>‘success‘, ‘msg‘=>$photo,//返回給前台顯示 )); }else{ throw new Exception("圖片不可為空"); } }catch (Exception $e){ return json_encode(array( ‘status‘ => ‘error‘, ‘msg‘ => $e->getMessage(), )); } } /** * @param $filename 上傳的檔案名稱 * @return mixed 返迴文件尾碼 */ private static function getExtension($filename) { $info = pathinfo($filename); return $info[‘extension‘]; } /** * @param $filesrcname源檔案名稱 * @param $filename臨時檔案名稱 * @throws Exception */ private static function checkImgExt($filesrcname,$filename) { $ext=self::getExtension($filesrcname); //對源檔案類型判斷 if(!in_array($ext, self::$ext)) { throw new Exception("上傳只能為圖片"); } $size=filesize($filename); if($size>=1024*1024){ throw new Exception("上傳圖片太大,不超過1MB"); } //判斷檔案名稱是否惡意更改 $magicFile = null; $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile); //3、圖片類型限制, if ($info) { $result = finfo_file($info, $filename); finfo_close($info); } if(!in_array($result, self::$type)){ throw new Exception("非法上傳檔案類型"); } }} View Code
相信圖片上傳對於一個web開發的程式員來說並不陌生,我自己之前也做了很多次圖片,但是好像一直都沒怎麼做過圖片驗證
private static function checkImgExt($filesrcname,$filename)是對上傳的圖片進行了一些驗證,PHP對於上傳的圖片,會根據php.ini中的配置,移動到$_FILES[‘file‘][‘tmp_name‘],
$_FILES[‘file‘][‘name‘]則是上傳的圖片原本的名字。
對於一些惡意程式,可能會選擇修改檔案的尾碼名,這樣可以逃過對$_FILES的驗證,在checkImgExt()中通過finfo_open可以擷取檔案MIME類型,這樣就可以檢查檔案尾碼名是不是有惡意更改。
yii對於繼承model的子類,都繼承了rules()方法,rules()方法也可以對檔案類型進行判斷,yii底層也是通過finfo_open的方式來進行驗證的。
yii2.0下,單圖片上傳到搜狐雲台以及圖片上傳到本機。