M
M
MaikMain2018-04-08 14:07:55
Yii
MaikMain, 2018-04-08 14:07:55

How to upload a file to the server. Yii2?

Good afternoon
I have such a problem, I need to upload a text file to the server and write the file name with the extension to the database. I tried a bunch of methods described on the Internet, nothing helped.
Then I tried to do it the way Maxim Timofeev showed in his videos , but it didn’t help either.
I added this alias:

Yii::setAlias('@books', dirname(dirname(dirname(__DIR__))) . '/public_html/uploads/books/');

Whole Book model:
The whole Book model
<?php

namespace common\models;

use Yii;
use yii\helpers\Url;
use yii\web\UploadedFile;

class Book extends \yii\db\ActiveRecord
{

    const IMAGES_SIZE = [
        ['50', '50'],
    ];
    public $file;
    public $bookfile;

    public static function tableName()
    {
        return 'book';
    }

    public function rules()
    {
        return [
            [['category_id', 'author_id', 'name', 'language', 'year', 'status'], 'required'],
            [['category_id', 'year', 'status'], 'integer'],
            [['content'], 'string'],
            [['name', 'language', 'keywords', 'description', 'bookfile'], 'string', 'max' => 255],
            [['author_id'], 'string', 'max' => 50],
            [['image'], 'string', 'max' => 100],
            [['file'], 'image'],
            [['bookfile'], 'file', 'extensions' => 'txt,docx,pdf,fb2'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => '№',
            'category_id' => 'Категория',
            'author_id' => 'Автор',
            'name' => 'Название',
            'content' => 'Текс',
            'language' => 'Язык',
            'year' => 'Год',
            'keywords' => 'Ключевые слова',
            'description' => 'Описание',
            'bookfile' => 'Книга',
            'smallImage' => 'Картинка',
            'image' => 'Картинка',
            'file' => 'Картинка',
            'statusName' => 'Статус',
            'status' => 'Статус',
        ];
    }

    public function getAuthor()
    {
        return $this->hasOne(Author::className(), ['id' => 'author_id']);
    }

    public function getCategory() {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    public function getFirstLetter() {
        return mb_substr($this->name, 0, 1, 'utf-8');
    }

    public static function getStatusList()
    {
        return ['Выкл', 'Вкл'];
    }

    public function getStatusName()
    {
        $list = self::getStatusList();
        return $list[$this->status];
    }

    public function getSmallImage() {
        if($this->image) {
            $path = str_replace('admin/', '', Url::home(true)).'uploads/image/book/50x50/'.$this->image;
        }
        else {
            $path = str_replace('admin/', '', Url::home(true)).'uploads/image/no-image.svg';
        }
        return $path;
    }

    public function beforeSave($insert)
    {
        if($file = UploadedFile::getInstance($this, 'file')){
            $dir = Yii::getAlias('@images').'/book/';
            if(file_exists($dir.$this->image)){
                @unlink($dir.$this->image);
            }
            if(file_exists($dir.'50x50/'.$this->image)){
                @unlink($dir.'50x50/'.$this->image);
            }
            $this->image = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6)  . '.' . $file->extension;
            $file->saveAs($dir.$this->image);
            $imag = Yii::$app->image->load($dir.$this->image);
            $imag->background('#fff',0);
            $imag->resize('50','50', Yii\image\drivers\Image::INVERSE);
            $imag->crop('50','50');
            $imag->save($dir.'50x50/'.$this->image, 90);
        }
        if($file = UploadedFile::getInstance($this, 'bookfile')){
            $dir = Yii::getAlias('@books');
            if(file_exists($dir.$this->bookfile)){
                @unlink($dir.$this->bookfile);
            }
            $this->bookfile = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6)  . '.' . $file->extension;
            $file->saveAs($dir.$this->bookfile);
        }
        return parent::beforeSave($insert);
    }

    public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            $dir = Yii::getAlias('@images').'/book/';
            if(file_exists($dir.$this->image)){
                @unlink($dir.$this->image);
            }
            foreach (self::IMAGES_SIZE as $size){
                $size_dir = $size[0].'x';
                if($size[1] !== null)
                    $size_dir .= $size[1];
                if(file_exists($dir.$this->image)){
                    @unlink($dir.$size_dir.'/'.$this->image);
                }
            }
            return true;
        } else {
            return false;
        }
    }
}

There is a lot of superfluous here, but there may be something with something somehow conflicting.
And this is the form:
<?php $form = ActiveForm::begin([
            'options' => ['enctype' => 'multipart/form-data'],
        ]); ?>
<?= $form->field($model, 'bookfile',['options' => ['class' => 'col-xs-12']])->fileInput() ?>
<?= $form->field($model, 'file',['options' => ['class' => 'col-xs-4']])->widget(FileInput::classname(), [
                            'options' => ['accept' => 'image/*'],
                            'pluginOptions' => [
                                'showCaption' => false,
                                'showRemove' => false,
                                'showUpload' => false,
                                'browseClass' => 'btn btn-primary btn-block',
                                'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
                                'browseLabel' =>  'Выбрать фото'
                            ],
                        ]);?>
<div class="form-group">
            <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>
        <?php ActiveForm::end(); ?>

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry, 2018-04-08
@MaikMain

Good afternoon.
In your Book model, everything is piled up. Both author data and image data.
You don't have to invent anything. Take the article from the documentation and make a separate model for loading the file.
And when it works for you, then it will think about how to combine it with other models.
This is first.
Secondly, what exactly does not work for you? What are the errors, warnings in the debug panel and browser console?
Are you sure the way

dirname(dirname(dirname(__DIR__))) . '/public_html/uploads/books/'
true?
Check what will show you
echo dirname(dirname(dirname(__DIR__))) . '/public_html/uploads/books/'
where is he taking you?

M
MaikMain, 2018-04-08
@MaikMain

The problem is solved, this lesson helped me personally: https://www.youtube.com/watch?v=2NOHrukCHBU

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question