首页 > 代码库 > YII上传图片完整代码
YII上传图片完整代码
//记住哦,还需要引人模板 <?php namespace app\controllers; use yii\web\Controller; use yii\web\UploadedFile; use app\models\Upload; //上传图片 public function actionUploada () { $model = new Upload(); $uploadSuccessPath = ""; if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, "file"); //文件上传存放的目录 $dir = "E:/wamp/www/yii/basic/uploads/".date("Ymd"); if (!is_dir($dir)) mkdir($dir); if ($model->validate()) { //文件名 $fileName = date("HiiHsHis").$model->file->baseName . "." . $model->file->extension; $dir = $dir."/". $fileName; $model->file->saveAs($dir); $uploadSuccessPath = "/uploads/".date("Ymd")."/".$fileName; } } return $this->render("upload", [ "model" => $model, "uploadSuccessPath" => $uploadSuccessPath, ]); }
//这个就是app/models/upload.php <?php namespace app\models; use Yii; use yii\web\UploadedFile; class Upload extends \yii\db\ActiveRecord { /** * @var UploadedFile|Null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [["file"], "file",], ]; } }
//这个是view <?php use yii\widgets\ActiveForm; $form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?> <?= $form->field($model, "file")->fileInput() ?> <button>Submit</button> <?php ActiveForm::end(); ?>
YII上传图片完整代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。