How to loop through multiple files and save the names within DB

I am using kartik file input extension and have it working for a single file/image upload how ever I am unsure on the function upload images.

I don’t really know how to loop through each image and save the images name/files into the DB (I have been trying for a while but not succeeded).

I have to columns for the image in my DB currently logo_img & logo_name (not sure if the latter is needed for multiple file uploads).

Current Model upload function (for single upload)




   /****** SOME CODE******/

   public $image;

  /****** SOME CODE******/

    public function uploadImage() {

        // get the uploaded file instance. for multiple file uploads

        // the following data will return an array (you may need to use

        // getInstances method)

        $image = UploadedFile::getInstance($this, 'image');


        // if no image was uploaded abort the upload

        if (empty($image)) {

            return false;

        }


        // store the source file name

        $this->logo_filename = $image->name;

        $ext = end((explode(".", $image->name)));


        // generate a unique file name

        $this->logo_img = Yii::$app->security->generateRandomString().".{$ext}";


        // the uploaded image instance

        return $image;

    }



View (for multiple file upload)




        echo $form->field($model, 'logo_filename');

         

        // your fileinput widget for single file upload

        echo $form->field($model, 'image[]')->widget(FileInput::classname(), [

            'options'=>['multiple' => true, 'accept'=>'image/*'],

            'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png']

        ]]);



Be cool if anyone had an existing solution maybe even commented that I could read and try to understand.

You should use this usefule extension : yii2-upload-behavior.

This will automatically save the image in the specific folder and save the image name in the DB.

And you can get the image URL with functions like “$model->getImageFileUrl(‘image’)” !

Hi sorry if my question was misleading, but I am stuck when trying to save an array/multiple images to database.

Maybe this doc can help you for uploading multiple files

Create a table ‘image’ and the Model Image.

And in your loop you can do something like this :




...

  foreach ($model->file as $file) {

    $image = new Image([

      'image' => $file->baseName

      //Other attributes ...

    ]);

    $image->save();

    $file->saveAs('images/'.$image->getPrimaryKey().'/'.$file->baseName);

  }

...



It only save single image for me can you explain why?

public function actionMultiple(){
        $model = new Media;
        $model->post_id = '2';
        if (Yii::$app->request->ispost) {
            $model->media = UploadedFile::getInstances($model, 'media');
            if ($model->media) {
                foreach ($model->media as $value) {
                    $BasePath = Yii::$app->basePath.'/../images/post_images';
                    $filename = time().'-'.$value->baseName.'.'.$value->extension;
                    $model = new Media([
                        'post_id' => '2',
                        'media' => $filename
                    ]);
                    $model->save();
                    $value->saveAs($BasePath.$filename);
                    return array('status' => true, 'message' => 'Image Saved');
                }
                return array('status' => ture, 'message' => 'Not saved');
            }
        }
        return array('status' => true, 'data' => $model);
    }

I use the kartik multiple file extension to receive multiple files. I started with the basic file upload model described in the Yii2 guide found here: Yii2 File Upload and add a loop to save multiple files and I change the attribute ‘imageFile’ to ‘imageFiles’. I use another model, Image, to save the names of the files. A simplified version of my upload action from my SiteController:

public function actionUpload()
{
$model = new UploadForm();
$post = Yii::$app->request->post('UploadForm');
if(isset($post)) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
      if ($model->upload()) {
         foreach($model->imageFiles as $file) 
	 {
	     $image = new Image;
	     $image->name = $identifier.'-'.$file->name;
	     $image->save();
         }	
  return $this->redirect([VIEW]);
        }
	else {
		throw new UserException("Error Message.");
	}
    }

Where the files get saved is in the part that says $model->upload(), which calls the upload function in the UploadForm model.

 public function upload()
{
    if ($this->validate()) {
        foreach ($this->imageFiles as $file) {
	$fileName = preg_replace('/[^A-Za-z0-9\. -]/', '', $file->baseName);
            $file->saveAs('uploads/'. $fileName . '.' . $file->extension);
        }
        return true;
    } else {
        return false;
    }
}

I think your issue may be calling your Media model at the beginning and then again inside the loop.