標籤:超過 return render tin lse save NPU backend UNC
//模型
<?phpnamespace backend\models;use Yii;use yii\web\UploadedFile;class UploalModel extends \yii\db\ActiveRecord{ /** * @var UploadedFile|Null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [["file"], "file",], ]; } /**公用上傳 上傳資訊(數組) 檔案名稱 大小 尾碼名限制 上傳後儲存的名字 update時為更新圖片 刪除原有圖片*/ public function upload($img,$name = ‘/vessel‘,$siez = ‘‘,$arr_type = ‘‘,$text_name = ‘‘,$act=‘update‘,$url=‘/vessel/20180831/153571385083726.jpg‘) { $path = ‘../..‘; $dirname = $path.$name; $fill=$this->file->extension;//圖片的名字只取尾碼名 if(empty($text_name)){ $ran=time().rand(10000,99999);//隨機名字 }else{$ran = $text_name;} $arr = $arr_type; if(!empty($arr)){ if(!in_array($fill,$arr)){ return json_encode(‘格式不正確‘);} } //定義上傳大小和類型 if(!empty($siez)){ if($img[‘size‘]>$siez) {return json_encode(‘檔案大小超過限制‘);} } //檔案上傳存放的目錄 $dir=$dirname.‘/‘.date("Ymd"); $dir_sev=$name.‘/‘.date("Ymd");/*資料庫儲存路徑*/ if(!file_exists($dir)) { mkdir($dir,0777,true); } if ($this->validate()) { //檔案名稱 $fileName = $ran .‘.‘.$fill; $dir = $dir."/". $fileName; if($act == ‘update‘){if($this->file->saveAs($dir)){@unlink($path.$url);}}/*刪除圖片*/ $uploadSuccessPath = $dir_sev."/". $fileName;/*最後路徑*/ return $uploadSuccessPath; } }}
//控制器
<?phpnamespace backend\controllers;use Yii;use backend\models\UploalModel;use yii\web\UploadedFile;class TestController extends \yii\web\Controller{ /** * 檔案上傳 * 我們這裡上傳成功後把圖片的地址進行返回 */ public function actionIndex () { $model = new UploalModel(); $uploadSuccessPath = ""; if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, "file"); $file = $model->upload((array)$model->file); return $file; } return $this->render("index", [ "model" => $model, "uploadSuccessPath" => $uploadSuccessPath, ]); }}
//視圖
<?phpuse yii\widgets\ActiveForm;$form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]);?> <input type="hidden" name="UploalModel[file]" value=""> <input type="file" id="uploalmodel-file" name="UploalModel[file]"> <button>Submit</button><?php ActiveForm::end(); ?>
yii2檔案上傳