uploading images in Yii, error $model->save() - php

Im trying to upload images and add to db file name and now Im stuck, because it wont add entry to db.
Error in debugger is Property "EeCarTypes.foto" is not defined.
controllers relavent code:
public function actionCreate()
{
$model=new EeCarTypes;
$path = Yii::app()->basePath . '/../images/upload/cartypes';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['EeCarTypes']))
{
$model->attributes=$_POST['EeCarTypes'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs( $path . '/adsfasdfadf' );
}
}
$this->render('create', array('model'=>$model));
}
view code:
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and model code:
public $image;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'ee_car_types';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array( 'image', 'file', 'types' => 'jpg, gif, png'),
array('car_type', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, car_type', 'safe', 'on'=>'search'),
);
}
I think anything else is irelevent here. Please help me :)

**Replace your view code**
echo $form->fileField($model, 'image');
with
<?php echo CHtml::activeFileField($model, 'image'); ?>
**In your controller file**
if(isset($_POST['EeCarTypes']))
{
$rnd = rand(0,9999);
$model->attributes=$_POST['EeCarTypes'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
$model->attributes=$_POST['EeCarTypes'];
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/upload/cartypes'.$fileName);
$this->redirect(array('index'));
}
}

At your model you should create a name property for the image and the field at the database. Then assign the file name to this property at your action method before you call the save(), like this:
$file = CUploadedFile::getInstance($model,'image');
$model->image_name = $file->name;
//use this if you want to save the file type but first create the image_type property
$model->image_type = $file->type;
[...]

Create an attribute with the name foto in your model EeCarTypes and look here

Related

Upload files with different attributes in Yii2 ActiveForm

I have a Yii2 ActiveForm with two form field that accepts file input.
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput() ?>
In the controller i have:
public function actionCreate()
{
$model = new Product();
$model->supplier_id = Yii::$app->user->identity->id;
$imageArray = ['mainImage','productImage'];
$mainImageIndex = 1;
if ($model->load(Yii::$app->request->post())) {
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
$model->images = $model->singleImageUpload();
//UploadedFile::reset();
// var_dump($model->mainImage);
// exit();
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$images = $model->multipleImageUpload();
$imageCount = count($images);
if ($model->validate() && $model->save(false)) {
for ($i=0; $i < $imageCount; $i++) {
$imageModel = new ProductImage();
$imageModel->product_id = $model->id;
$imageModel->image = $images[$i];
$imageModel->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
In the Model class, I have these validations rules:
[['mainImage','productImage'], 'safe'],
[['mainImage','productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
Every time i submit the form I get an error of mainImage field stating Please upload a file. There is no error for productImage
What could be the possible fix for this?
Edit
Images for mainImageand productImage are successfully uploaded though the validation error persists on for the mainImage
The problem was validation in the model class.
I had marked them as safe
[['mainImage','productImage'], 'safe'],
I commented out this validation and it worked
If you want to upload multiple files then you needed to change your view
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
And your rule in model says that you have been trying to upload multiple image for attributes productImage[] and mainImage. But view says that attribute mainImage used for single file so change the rule.
[['mainImage'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png'],
[['productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
In controller,
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
if ($model->multipleImageUpload()) {
// file is uploaded successfully
return;
}
In your model,
public function multipleImageUpload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
For more reference please go through this link: https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload

FileUpload to upload image fail to save the image, but no error message displayed

I'm using Yii2 basic. It doesn't seems like anything's wrong, no error message displayed, but why did my image didn't upload? The rest (title, content etc) get uploaded through the form,though
This is my model's rule and related method:
public $image;
public function init(){
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/batam/';
Yii::$app->params['uploadUrl'] = Yii::$app->urlManager->baseUrl . '/uploads/batam/';
}
public function rules()
{
return [
[['title', 'content'], 'required'],
[['content'], 'string'],
[['created_at', 'updated_at','image'], 'safe'],
[['image'], 'file','extensions'=>'jpg,png,jpeg'],
[['title'], 'string', 'max' => 255],
];
}
public function getImageFile()
{
return isset($this->image) ? Yii::$app->params['uploadPath'].$this->image : null;
}
public function uploadImage() {
$image = UploadedFile::getInstance($this, 'image');
if (empty($image)) {
return false;
}
$this->image = $image->name;
return $image;
}
This is my controller
public function actionCreate()
{
$model = new News();
if ($model->load(Yii::$app->request->post()) )
{
// process uploaded image file instance
$image = $model->uploadImage();
if($model->validate())
{
if($model->save())
{
// upload only if valid uploaded file instance found
if ($image !== false)
{
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', 'id'=>$model->id]);
}
}
else{echo " validation is failed";}
}
else{
return $this->render('create', [
'model' => $model,
]);
}
}
This is the form
echo $form->field($model, 'image')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
'pluginOptions' => [['previewFileType' => 'any']]
]);
I had included the enctype also at the beginning of the form
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
At this point inside the if ($image !== false) part of the controller , the $image and $path to be saved-as contains a seemingly correct path.
This is my $path : C:\xampp\htdocs\gbia/uploads/batam/test image 1-01.jpg and my $image also contain the object (not null). This is the var_dump of my $image :
object(yii\web\UploadedFile)#179 (5) { ["name"]=> string(19) "test image 1-01.jpg" ["tempName"]=> string(24) "C:\xampp\tmp\php3199.tmp" ["type"]=> string(10) "image/jpeg" ["size"]=> int(925184) ["error"]=> int(0) }
I think something wrong with the saveAs(), but I can't figure it out. Had googled around, look on stackoverflow and tutorials but I still can't find any answer. Can someone help? Thanks
Check your model, you have declared $image as a public variable of the class, and not as a field in the database, if you want to store the data there, it will never work, as the public property that is temporary will have preference over the database column.
public $image;
So delete this field (If it is also in the db) or generate a new column name (I suggest by the name of path).
[['content', 'path'], 'string'],
Then you need to store the path, I don't see where are you doing that in the controller or class. I suggest you to add a field in the database with the "path" name and then do like this in the controller:
$path = $model->getImageFile();
$image->saveAs($path);
$model->path = $path . $image // You must store the full path plus the file name
$model->save(); // then you save the model again
Any doubt is welcome, I have example projects that I can show you if you are unable to see the light.

CUploadedFile in yii

my problem is with two or more files.
this codes is form Yii application development cookbook(2nd edition), chapter 4
i use Yii 1.1.14
controller:
<?php
class UploadController extends Controller
{
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$files=CUploadedFile::getInstances($model,'file');
if($model->validate()){
foreach($files as $file)
$file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'dir' => $dir,
));
}
}
model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return [
['file', 'file', 'types'=>'jpg'],
];
}
}
view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form- data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, "[0]file")?>
<?php echo CHtml::activeFileField($model, "[1]file")?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
help me, please
You should fix form enctype, use multipart/form-data instead of multipart/form- data.
You could use CMultiFileUpload
controller:
$images = CUploadedFile::getInstancesByName('image');
foreach ($images as $image => $pic) {
}
view:
$this->widget('CMultiFileUpload', array(
'name' => 'image',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
));
Add to model 'maxFiles' param, if you need validation to work properly for multifiles upload.
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,gif,png', 'maxSize'=>'204800', 'allowEmpty'=>true, 'maxFiles'=>4),
);
}

yii how to change uploaded file name

I want to upload a image and change the original name then save it.
Model:
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
Controller:
$model->image = CUploadedFile::getInstanceByName('image');
If i save it without any other actions it will work.
But how could i change the name of image ? I try something like below:
$model->image->name = "xxx"; //CUploadedFile.name readonly
if($model->save())
$model->images->saveAs(some_path_else.newname); //the files's new name is different from database
$model->image = "abc.jpg"; //wont save it
Is the image attribute must be an instance of CUploadedFile?
Anyone help pls
do something like this
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if (!empty($uploadedFile)) {
//new name will go here
$model->image = strtotime($this->getCurrentDateTime()) . '-' .$uploadedFile;
}
//this will save the image with new name
$uploadedFile->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);
Thanks for your answer.
I figured it out.
CUploadedFile.name is read only , so i can't change it.
The Model need a new public attribute :
public $file;
public function rules()
{
return array(
array('file', 'file', 'types'=>'jpg, gif, png'),
array('iamge', 'length'=>'255'),
);
}
Then in the controller:
$model->file = CUploadedFile::getInstanceByName('image');
$model->file->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);
$model->image = $model->file->name;
It's works fine.(it's not real code)
see here

How To Upload A File Using A Model in yii?

i have read this article http://yiiframework.com/wiki/2
and i have done everything step by step .
but it's not working !
this is the model which i just copy and then paste :
class Item extends CActiveRecord
{
public $image;
// ... other attributes
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
}
my view is exactly the same as the article :
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and my controller is :
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs(dirname(__FILE__).'/a.txt');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
when i choose an image(jpg , png , or something else) the controller doesn't see my file , i mean isset($_FILES['Item']) is false ... i know it's false because i check it with var_dump hundreds of times :
public function actionCreate()
{
$model=new Item;
var_dump(isset($_POST['Item']));
...
i also test var_dump(isset($_FILES['Item'])) which was false either .
for every kinds of file(except plain txt file) $_POST['Item']) remains empty.
i checked my request using firebug network panel(both Firefox and chrome) and the request had the file .
i have already check this question , seems it's the same problem but the answers wasn't useful because CUploadedFile::getInstance and CUploadedFile::getInstanceByName are also return null for my case
what do you think ?
The Problem was not related to Yii Framework or my php code because i just test the same code on two different machine and that works just fine .
i am using wamp on my own computer and i guess the problem was something related to Apache or php configurations.
In controller change and use like this:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$uploadedFile = CUploadedFile::getInstance($model,'image');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/images/'. $model->image);
// redirect to success page
}
}
}
$this->render('create', array('model'=>$model));
}
}

Categories