简体   繁体   中英

Yii2 Uploading Multiple Files Not Working

I managed to try one out but it's not working in my end: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

There's no error message and the data are not saved in the database (MongoDB). Here are my code snippets:

Contact.php Model

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 Controller

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 View

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
    ],
]);

I'm not sure what seems to be lacking or wrong. Is it because I am using MongoDB or Kartik's widget? Please let me know your thoughts below.

I finally got it. Here's what I did:

$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(); 

First off, I forgot that it should be getInstances() with an 's' since it's a multiple file upload. Then I put the code in a foreach loop then used implode to save the urls/paths as strings separated by a comma.

From the article you posted:

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

The upload method is in the first code block and saves the file on the filesystem

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

If you want to save it as binary to your Database, you'd need to read the contents of the file (eg file_get_contents ) and assign it to the model attribute.

Note that, if you're using a standard ActiveForm, you need to tell it that it's expecting multiple files, eg:

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

rather than:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM