How to upload files in yii2?

巴扎黑
Release: 2023-03-15 10:24:01
Original
5031 people have browsed it

How to upload files in yii2?

Yii2 UploadedFile implements file upload

To upload files in Yii, you usually use the yii\web\UploadedFile class, which Encapsulate each uploaded file into an UploadedFile object. Combining yii\widgets\ActiveForm and models, you can easily implement a secure file upload mechanism.

#1. Single file upload

First create a model models/UploadForm.php with the following content

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'],
        ];
    }
}
Copy after login

Create another view file with the following content



 ['enctype' => 'multipart/form-data']]) ?>

field($model, 'file')->fileInput() ?>



Copy after login

Finally create a controller file with the following content

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]);
    }
}
Copy after login

Note that we do not use model->load(...) here, but use UploadedFile::getInstance(...). The difference is that the latter will not execute $model->validate(), so you need to manually execute $model->validate() to check the validity of the data. If the verification passes, the uploaded file is saved in the uploads folder, that is, uploads in the web directory.

Some optional configuration options
The uploaded file cannot be empty

public function rules(){
    return [
        [['file'], 'file', 'skipOnEmpty' => false],
    ];
}
Copy after login

The upload type can be checked not only based on the extension, but also based on the content of the file

public function rules(){
    return [
        [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
    ];
}
Copy after login

2. Multiple file upload

If you want to upload multiple files at one time, you only need to adjust a few parameters to achieve the goal

Model:

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!
        ];
    }
}
Copy after login

View:

 ['enctype' => 'multipart/form-data']]);
?>

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

    

Copy after login

The difference from single file upload is the following sentence

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

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, 'file');

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

        return $this->render('upload', ['model' => $model]);
    }
}
Copy after login

This way, multiple files can be uploaded.

For more related knowledge, please visit PHP Chinese website! !

The above is the detailed content of How to upload files in yii2?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!