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.
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.