1

Есть в одной форме два FileInput. Один загружает картинки, а другой текстовые файлы. Все лишнее я вырезал, для лучшей читабельности. В контроллере пишу:

    public function actionUpdate($id) {
        $model = new Book();
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->image = UploadedFile::getInstance($model,'image');
            if( $model->image ) {
                $model->uploadImg();
            }
            $model->bookfile = UploadedFile::getInstance($model, 'bookfile');
            if( $model->bookfile ) {
                $model->uploadFile();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }
        else {
            return $this->render('update', compact('model'));
        }
    }
В моделе пишу:

    public $image;
    public $bookfile;
    public function rules() {
        return [
            [['image'],'file','extensions' => 'png, jpg'],
            [['bookfile'],'file','extensions' => 'txt,doc,pdf'],
        ];
    }
    public function uploadImg() {
        if($this->validate()) {
            $path = 'upload/store/'.$this->image->baseName.'.'.$this->image->extension;
            $this->image->saveAs($path);
            $this->attachImage($path, true);
            @unlink($path);
            return true;
        }
        else { return false; }
    }
    public function uploadFile() {
        if($this->validate()) {
            $ext = end((explode(".", $this->bookfile->name)));
            $this->bookfile = Yii::$app->security->generateRandomString().".{$ext}";
            $path = Yii::getAlias('@webroot').'/upload/global/books/'.$this->bookfile;
            $this->bookfile->saveAs();
        }
        else {  return $this->redirect(['index']); }
    }

Картинку прикрепляю с помощью расширения от CostaRico, yii2-images. Проблема в том, что когда все строки заполнил и добавляю картинку(без загрузки текстового файла), то картинка успешно загружается. Если все строки заполнил и добавляю загрузку текстового файл (без картинки), то файл успешно загружается. Если же я указываю загрузку обоих файлов, то вылетает ошибка:

finfo_file(D:\OpenServer\userdata\temp\phpD547.tmp): failed to open stream: No such file or directory

Подскажите в чем проблема? Разрабатываю сайт на Yii2 basic

5
  • а зачем вы сгенерировали $path в uploadFile() если потом ее не используете?
    – WebCoder
    2 дек 2016 в 14:26
  • @WebCoder - Спасибо за замечание, теперь в uploadFile() написал: $this->bookfile->saveAs($path); И все равно тоже самое
    – DangerPro
    3 дек 2016 в 16:16
  • Если честно я не могу понять почему оно должно сохранить. Смотрите вы изначально в свойство $this->bookfile присваиваете рандомное имя ( тоесть на данный момент это string ) , после вы пытаетесь вызвать у свойства некий метод для сохранения. тоесть вы пытаетесь сохранить строку как файл. Возможно я не прав. посмотрите перед $this->bookfile->saveAs(); что находится в bookfile
    – mydls1
    11 мая 2017 в 15:25
  • только заметил . попробуйте изменить имя переменной public $bookfile на другое. потому что вы затераете файл
    – mydls1
    11 мая 2017 в 15:31
  • или измените эту строку $this->bookfile = Yii::$app->security->generateRandomString().".{$ext}"; . вы когда принимаете модель , в свойстве $this->bookfile у вас file','extensions' => 'txt,doc,pdf'
    – mydls1
    11 мая 2017 в 15:32

1 ответ 1

0
        public $image;
        public $bookfile;
        public $bookfileName
        public function rules() {
            return [
                [['image'],'file','extensions' => 'png, jpg'],
                [['bookfile'],'file','extensions' => 'txt,doc,pdf'],
            ];
        }
        public function uploadImg() {
            if($this->validate()) {
                $path = 'upload/store/'.$this->image->baseName.'.'.$this->image->extension;
                $this->image->saveAs($path);
                $this->attachImage($path, true);
                @unlink($path);
                return true;
            }
            else { return false; }
        }
        public function uploadFile() {
            if($this->validate()) {
                $ext = end((explode(".", $this->bookfile->name)));
                $this->bookfileName = Yii::$app->security->generateRandomString().".{$ext}";
                $path = Yii::getAlias('@webroot').'/upload/global/books/'.$this->bookfileName;
                $this->bookfile->saveAs($path);
            }
            else {  return $this->redirect(['index']); }
        }

попробуйте так

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.