A-A+

yii2用表单上传文件的方法(多文件上传方法)

2017年02月09日 19:08 汪洋大海 暂无评论 阅读 76 views 次

1、单个文件上传

首先建立一个模型models/UploadForm.php,内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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'],
        ];
    }
}

再建立一个视图文件,内容如下

1
2
3
4
5
6
7
8
9
10
11
<?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() ?>

最后建立控制器文件,内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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里。

一些可选的配置选项
上传文件不能为空

1
2
3
4
5
6
public function rules()
{
    return [
        [['file'], 'file', 'skipOnEmpty' => false],
    ];
}

上传类型,不仅可以根据扩展名检验,还可以根据文件的内容进行检验

1
2
3
4
5
6
public function rules()
{
    return [
        [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
    ];
}

2、多文件上传

如果你想一次上传多个文件,只需调节几个参数就可以达到目的

Model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class UploadForm extends Model
{
    /**
     * @var UploadedFile|Null file attribute
     */
    public $file;
 
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'maxFiles' => 10], // <--- here!
        ];
    }
}

View:

1
2
3
4
5
6
7
8
9
10
11
<?php
use yii\widgets\ActiveForm;
 
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
 
<?= $form->field($model, 'file[]')->fileInput(['multiple' => true]) ?>
 
    <button>Submit</button>
 
<?php ActiveForm::end(); ?>

与单文件上传不同的是下面这句

1
$form->field($model, 'file[]')->fileInput(['multiple' => true])

Controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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::getInstances($model, 'file');
 
            if ($model->file && $model->validate()) {
                foreach ($model->file as $file) {
                    $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
                }
            }
        }
 
        return $this->render('upload', ['model' => $model]);
    }
}

这样就可以实现多文件上传了。
参考https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

原文地址:
http://www.yiichina.com/tutorial/328

必须手工先建立uploads目录,不然会出错。

1
 $filePath = $this->fileExists(Yii::$app->basePath.'/uploads/');  //上传路径
1
2
3
4
5
6
public function fileExists($uploadpath){
    if(!file_exists($uploadpath)){
        mkdir($uploadpath);
    }
    return $uploadpath;
}

某个不错CMS地址:http://git.oschina.net/liufee/cms

标签:

给我留言