Yii2上传多个文件不起作用

时间:2015-09-23 05:38:55

标签: php mongodb file-upload yii2 multiple-file-upload

我设法尝试了一次,但它没有在我的工作中完成:http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

没有错误消息,数据未保存在数据库(MongoDB)中。这是我的代码片段:

Contact.php 型号

class Contact extends ActiveRecord
{
    public $file;

    public $attachment;

    /**
     * @inheritdoc
     */
    public static function collectionName()
    {
        return ['iaoy', 'contact'];
    }

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return [
            '_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort', 'urls'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort', 'urls'], 'safe'],
            [['fname','lname','contact_type','business_name'], 'required'],
            [['attachment'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 10, 'maxSize'=>20*1024*1024,],
            //[['urls'],'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            //'contact_id' => 'Contact ID',
            '_id' => 'Contact ID',
            'contact_type' => 'Contact Type',
            'business_name' => 'Business Name',
            'fname' => 'First Name',
            'lname' => 'Last Name',
            'email' => 'Email',
            'phone' => 'Phone',
            'address' => 'Address',
            'notes' => 'Notes',
            'attachment' => 'Attachment',
            'company_id' => 'Company ID',
        ];
    }

    public function upload()
    {
        if ($this->validate()) { 
            foreach ($this->attachment as $file) {
                $file->saveAs('archive/contact/' . $file->baseName . '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    }
}

ContactController.php 控制器

public function actionCreate()
{
    $session = Yii::$app->session;      
    $model = new Contact();

    if($model->load(Yii::$app->request->post())) {
    //if (Yii::$app->request->isPost) {
        $model->company_id = new \MongoId($session['company_id']);

        date_default_timezone_set('Asia/Manila');
        $model->date_added = date('d-m-Y', time());

        $model->attachment = UploadedFile::getInstance($model, 'attachment');
        /*if($model->attachment) {
            foreach ($model->attachment as $key => $file) {
                $file->saveAs('archive/contact/'. $file->baseName . '.' . $file->extension); //Upload files to server
                $model->urls .= 'archive/contact/' . $file->baseName . '.' . $file->extension.'**'; //Save file names in database- '**' is for separating images
            }

            $path = 'archive/contact/' . $model->attachment->baseName . '.' . $model->attachment->extension;

            $count = 0;
            {
                while(file_exists($path)) {
                    $path = 'archive/contact/' . $model->attachment->baseName . '_'.$count.'.' . $model->attachment->extension;
                    $count++;
                }
            }
            $model->attachment->saveAs($path);
            $model->attachment =  $path;
        }*/

        $model->save(); 

        if($model->save()) {
            Yii::$app->session->setFlash('success', "Successfully created contact!");
        } else {
            $model->save();                  
            if($model->save()) {
                Yii::$app->session->setFlash('success', "Successfully created contact!");
            } else {
                Yii::$app->session->setFlash('error', "Contact creation failed!");
            }
        }

        $model->refresh();
        return $this->redirect(['index', 'id' => $session['user_id']]);

    } else {
        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }   
}

_form.php 查看

echo FileInput::widget([
    'model' => $model,
    'attribute' => 'attachment[]',
    'name' => 'attachment[]',
    'options' => [
        'multiple' => true,
        'accept' => 'image/*'
    ],
    'pluginOptions' => [
        'showCaption' => false,
        'showRemove' => false,
        'showUpload' => false,
        'browseClass' => 'btn btn-primary btn-block',
        'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
        'browseLabel' =>  'Attach Business Card',
        'allowedFileExtensions' => ['jpg','gif','png'],
        'overwriteInitial' => false
    ],
]);

我不确定什么似乎缺乏或错误。是因为我使用的是MongoDB或Kartik的小部件吗?请在下面告诉我你的想法。

3 个答案:

答案 0 :(得分:2)

我终于明白了。这就是我的所作所为:

$model->attachment = UploadedFile::getInstances($model, 'attachment');

if ($model->attachment) {
    foreach ($model->attachment as $attachment) {
        $path = 'archive/contact/' . $attachment->baseName . '.' . $attachment->extension;
        $count = 0;
        {
            while(file_exists($path)) {
               $path = 'archive/contact/' . $attachment->baseName . '_'.$count.'.' . $attachment->extension;
               $count++;
            }
        }
        $attachment->saveAs($path);
        $files[] = $path;
    } 
    $model->attachment = implode(',', $files);
}

$model->save(); 

首先,我忘记了getInstances()应该是foreach的&#39;因为它是一个多文件上传。然后我将代码放在implode循环中,然后使用gcloud init projectname将urls / paths保存为以逗号分隔的字符串。

答案 1 :(得分:0)

从您发布的文章:

if (Yii::$app->request->isPost) {
    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    if ($model->upload()) {
        // file is uploaded successfully
        return;
    }
}

上传方法位于第一个代码块中,并将文件保存在文件系统上

public function upload()
{
    if ($this->validate()) {
        $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
        return true;
    } else {
        return false;
    }
}

如果要将其作为二进制文件保存到数据库,则需要读取文件的内容(例如file_get_contents)并将其分配给模型属性。

答案 2 :(得分:0)

请注意,如果您使用的是标准ActiveForm,则需要告知它需要多个文件,例如:

echo $form->field($modelImage, 'imageFiles[]')->fileInput(['multiple' => true]);

而不是:

echo $form->field($modelImage, 'imageFiles')->fileInput(['multiple' => true]);