yii2檔案上傳

來源:互聯網
上載者:User

標籤:超過   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檔案上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.