无法使用yii2

时间:2017-01-24 11:04:22

标签: php file-upload yii2-advanced-app

我正在尝试使用拖放功能上传多个文件。我在点击save()时得到了数组,但它无法上传它抛出:

  

调用数组

上的成员函数SaveAs()

_form.php这个

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use backend\models\Users;
use yii\helpers\Arrayhelper;
use kartik\file\FileInput;
use yii\web\UploadedFile;
use yii\helpers\Url;

?>

<div class="album-form">

     <?php $form = ActiveForm::begin([
            'options' => ['enctype' => 'multipart/form-data'],
            'id' => $model->formName(),
            'enableAjaxValidation' => true,

        ]); ?>

<?php  echo FileInput::widget([
            'name' => 'albummediaFile[]',
            'options'=>[
                'multiple'=>true,
            ],
            'pluginOptions' => [
                'maxFileCount' => 10,
                'showUpload' => false,
                'maxFileSize'=>2000,
                'allowedFileExtensions' => ['jpg', 'png','jpeg'],
            ]
        ]);
    ?>

AlbumController.php(控制器)

    public function actionCreate()
    {
        $model = new Album();
        $modelalbummedia = new Albummedia(); 


        if ($model->load(Yii::$app->request->post())) {


          $modelalbummedia->albummediaFile = UploadedFile::getInstances($modelalbummedia, 'albummediaFile');

                    if ($modelalbummedia->upload()) {

                        return;
                    }
                      $modelalbummedia->save();
                    }


            $model->save();

            return $this->redirect(['view', 'id' => $model->albumID]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                    'modelalbummedia' => $modelalbummedia,
                ]);
            }

    }

Albummedia.php(型号)

public function upload()
    {
        if ($this->validate()) { 
            foreach ($this->albummediaFile as $file) {
                $file->saveAs('uploads/Album_Media/' . $file->baseName . '.' . $file->extension);

                $model->albummediaFile = $_FILES['albummediaFile']; **Not getting file name here.
            }
            return true;
       } else {
           return false;
        }
    }

1 个答案:

答案 0 :(得分:0)

改变你的:

for($i=0;$i<count($_FILES['albummediaFile']['name']);$i++){

为:

foreach($modelalbummedia->albummediaFile as $file) {

在循环内部使用$file代替$modelalbummedia->albummediaFile

复制并粘贴代码:

    $modelalbummedia->albummediaFile = UploadedFile::getInstances($modelalbummedia, 'albummediaFile');
    if($modelalbummedia->albummediaFile){
        foreach($modelalbummedia->albummediaFile as $file){
            $imagepath = 'uploads/Album_Media/';
            $random_value = rand(000,999).time();
            $file->SaveAs($imagepath.$random_value.$file->baseName);
            $file = $random_value.$file->baseName;
        }
      $modelalbummedia->save();
    }