yii2: 上传图片,生成目录
1、单个文件上传
首先建立一个模型models/UploadForm.php,内容如下
namespace app\models; use yii\base\Model; use yii\web\UploadedFile; /** * UploadForm is the model behind the upload form. */ class UploadForm extends Model { /** * @var UploadedFile file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file'], ]; } }
再建立一个视图文件,内容如下
<?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'file')->fileInput() ?> <button>Submit</button> <?php ActiveForm::end() ?>
最后建立控制器文件,内容如下
namespace app\controllers; use Yii; use yii\web\Controller; use app\models\UploadForm; use yii\web\UploadedFile; class SiteController extends Controller { public function actionUpload() { $model = new UploadForm(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, 'file'); if ($model->file && $model->validate()) { $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension); } } return $this->render('upload', ['model' => $model]); } }
注意这里我们没有用model->load(...),而是用了UploadedFile::getInstance(...)。区别是后者不会执行$model->validate(),所以需要手动的去执行$model->validate()来检验数据的合法性。如果检验通过了,上传的文件保存在uploads文件夹下,即web目录下的uploads里。
一些可选的配置选项
上传文件不能为空
public function rules() { return [ [['file'], 'file', 'skipOnEmpty' => false], ]; }
上传类型,不仅可以根据扩展名检验,还可以根据文件的内容进行检验
public function rules() { return [ [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',], ]; }
目录生成:
/** * 上传图片 * @return string */ private function uploadPic() { //是否上传图片 //upload $file_img = ''; $file_name = md5(time()); $path = 'uploads/'.date("Y").'/'.date("m").'/'.date('d').'/'; if (!file_exists($path)) { $this->createDir($path); } if (Yii::$app->request->isPost) { $model = new WexinUploadForm(); $model->file = UploadedFile::getInstance($model, 'file'); if ($model->file && $model->validate()) { $back = $model->file->saveAs($path .$file_name. '.' . $model->file->extension); if($back) $file_img = $path .$file_name. '.' . $model->file->extension; } } return $file_img; } /** * 递归:生成目录 */ private function createDir($str) { $arr = explode('/', $str); if(!empty($arr)) { $path = ''; foreach($arr as $k=>$v) { $path .= $v.'/'; if (!file_exists($path)) { mkdir($path, 0777); chmod($path, 0777); } } } }