yii2怎么实现文件上传?

巴扎黑
Lepaskan: 2023-03-15 10:24:01
asal
5203 orang telah melayarinya

yii2怎么实现文件上传?

Yii2 UploadedFile实现文件上传

在Yii里上传文件通常使用yii\web\UploadedFile类,它把每个上传的文件封装成 UploadedFile 对象。结合yii\widgets\ActiveForm和models,你可以轻松实现安全的上传文件机制。

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'],
        ];
    }
}
Salin selepas log masuk

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

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin([&#39;options&#39; => [&#39;enctype&#39; => &#39;multipart/form-data&#39;]]) ?>

<?= $form->field($model, &#39;file&#39;)->fileInput() ?>

<button>Submit</button>

<?php ActiveForm::end() ?>
Salin selepas log masuk

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

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, &#39;file&#39;);

            if ($model->file && $model->validate()) {                
                $model->file->saveAs(&#39;uploads/&#39; . $model->file->baseName . &#39;.&#39; . $model->file->extension);
            }
        }

        return $this->render(&#39;upload&#39;, [&#39;model&#39; => $model]);
    }
}
Salin selepas log masuk

注意这里我们没有用model->load(...),而是用了UploadedFile::getInstance(...)。区别是后者不会执行$model->validate(),所以需要手动的去执行$model->validate()来检验数据的合法性。如果检验通过了,上传的文件保存在uploads文件夹下,即web目录下的uploads里。

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

public function rules(){
    return [
        [[&#39;file&#39;], &#39;file&#39;, &#39;skipOnEmpty&#39; => false],
    ];
}
Salin selepas log masuk

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

public function rules(){
    return [
        [[&#39;file&#39;], &#39;file&#39;, &#39;extensions&#39; => &#39;jpg, png&#39;, &#39;mimeTypes&#39; => &#39;image/jpeg, image/png&#39;,],
    ];
}
Salin selepas log masuk

2、多文件上传

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

Model:

class UploadForm extends Model
{
    /**
     * @var UploadedFile|Null file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [[&#39;file&#39;], &#39;file&#39;, &#39;maxFiles&#39; => 10], // <--- here!
        ];
    }
}
Salin selepas log masuk

View:

<?php
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([&#39;options&#39; => [&#39;enctype&#39; => &#39;multipart/form-data&#39;]]);
?>

<?= $form->field($model, &#39;file[]&#39;)->fileInput([&#39;multiple&#39; => true]) ?>

    <button>Submit</button>

<?php ActiveForm::end(); ?>
Salin selepas log masuk

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

$form->field($model, &#39;file[]&#39;)->fileInput([&#39;multiple&#39; => true])
Salin selepas log masuk

Controller:

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, &#39;file&#39;);

            if ($model->file && $model->validate()) {
                foreach ($model->file as $file) {
                    $file->saveAs(&#39;uploads/&#39; . $file->baseName . &#39;.&#39; . $file->extension);
                }
            }
        }

        return $this->render(&#39;upload&#39;, [&#39;model&#39; => $model]);
    }
}
Salin selepas log masuk

这样就可以实现多文件上传了。

更多相关知识,请访问 PHP中文网!!

Atas ialah kandungan terperinci yii2怎么实现文件上传?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!