Problem downloading a file in Yii2

I am developing an application in a Yii2 framework.

I am uploading an image using the code below and which has worked so far. But now I got an error message. I do not understand what happened.

Below is the controller code where the files are downloaded and saved:

// Upload photo of subcategories...
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file) {
    $imageName = rand(1000,100000);
    $model->file->saveAs('uploads/subcategories/'.$imageName.'.'.$model->file->extension);
    $model->sub_category_photo = 'uploads/subcategories/'.$imageName.'.'.$model->file->extension;
}
$model->save();

I got the error below:

PHP warning - yii \ base \ ErrorException finfo_file (C: \ xampp \ tmp \ php9A7B.tmp): stream could not be opened: there is no such file or directory

I also do not comment extension = fileinfo.dllon the file php.iniand restart the server.

+4
source share
3 answers

I got solutions to these issues.

Call $model->save();in the controller

before

$model->file->saveAs();

The values ​​in the above code of my questions have changed below

// Upload photo of subcategories...
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file) {
    $imageName = rand(1000,100000);
    $model->sub_category_photo = 'uploads/subcategories/'.$imageName.'.'.$model->file->extension;
    $model->save();
    $model->file->saveAs('uploads/subcategories/'.$imageName.'.'.$model->file->extension);
} else {
    $model->save();
}

, -, ,

+7

> _form.php

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'image')->fileInput() ?>
<?php ActiveForm::end(); ?>

:

use yii\web\UploadedFile;

actionCreate():

if ($model->load(Yii::$app->request->post())){
    $model->image = UploadedFile::getInstance($model, 'image');            
    if($model->validate() && $model->save()) {                 
        $model->image->saveAs(dirname(__FILE__).'/../../uploads/'. $model->image);   
        $model->save(); 
    }
}

actionUpdate():

if ($model->load(Yii::$app->request->post()) ) {           
    $model->image = UploadedFile::getInstance($model, 'image');
    if($model->validate() && $model->save()){
        $model->image->saveAs(dirname(__FILE__).'/../../uploads/'.$model->image);   
        $model->save();
    }
}

actionDelete ($ id):

unlink($_SERVER["DOCUMENT_ROOT"]."/../../uploads/".$model->image);
+1
//Model Rule (note skip on empty):
['file', 'file', 'extensions' => 'jpg, jpeg, gif, png', 'mimeTypes' => 'image/jpeg, image/gif, image/png', 'skipOnEmpty' => true],

//save file
$model->file->saveAs();

//set it to null
$model->file = null;

//now it will save ok
$model->save();

I think what happens when the file is saved, it will be deleted from memory, so when the model tries to save, you get an error.

0
source

All Articles