Yii Framework store/save submitted file to images folder - php

Hi, for the past 2 days i've been reading and reading lots of tutorials about saving files to folders in Yii, and neither of them have worked so far. I have the folowing form:
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'htmlOptions' => array('enctype' => 'multipart/form-data')
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Binaryfile'); ?>
<?php echo $form->fileField($model,'uploadedFile'); ?>
<?php echo $form->error($model,'uploadedFile'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
endWidget(); ?>
The file field submits the code to a BLOB field in mysql database.
The Controller is as follows:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->binaryfile = CUploadedFile::getInstance($model,'binaryfile'); // grava na bd no campo binaryfile
// $model->binaryfile->saveAs(Yii::app()->params['uploadPath']);
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
And the Model is this one:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fileName', 'length', 'max'=>100),
array('fileType', 'length', 'max'=>50),
array('binaryfile', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, fileName, fileType, binaryfile', 'safe', 'on'=>'search'),
);
}
public $uploadedFile;
// Gravar imagem na base de dados - cria blob field
public function beforeSave()
{
if ($file = CUploadedFile::getInstance($this, 'uploadedFile'))
{
$this->fileName = $file->name;
$this->fileType = $file->type;
$this->binaryfile = file_get_contents($file->tempName);
}
return parent::beforeSave();
}
The code works fine to store a file as a BLOB field, but i need to change the code to store the file in images folder and next to display links that permits to open the file (pdf file) in any browser.
To store the file in images folder i tryed saveAs() in my controller actionCreate but Yii freezes and the webpage becames blank with no error, just blank.
**Anyone can help me... I need this very very much. Many thanks in advance. **

check this link,,in this link say how do it...
http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

Finally i've figured it by myself. The answer was rather simple, but took me 4 days to write it.
In my actionCreate() i did:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->uploadedFile=CUploadedFile::getInstance($model,'uploadedFile');
if($model->save())
$model->uploadedFile->saveAs("pdfs/".$model->uploadedFile,true);
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
**That way the saveAs() function worked like a charm and now saves my submited files in the pdfs folder.
The next step is to try and figure out how to create links for all files submitted to pdfs folder.
Maybe with a foreach() loop.
Best regards...**

Related

Yii file field posting empty values

I am a newbie in Yii, and I am trying to make an upload form in Yii, Please i need help.
Once the form post data to the controller every other post value is posted except for the file value.
i even tried checking for Errors with var_dump($model->image); and it returned this Error string '' (length=0) specifying an empty string like an image wasn't even posted at all.
This is my controller
class TestController extends Controller
{
public function actionIndex()
{
$model=new Test;
if(isset($_POST['Test']))
{
$model->attributes=$_POST['Test'];
if($model->save()){
var_dump($model->getErrors());
if ($model->image){
var_dump($model->image);
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = date("Y_m_d_H_i_s").$uploadedFile;
$model->image = $fileName;
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$fileName);
}
}
}
}
}
}
And this is my View
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'test-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
)); ?>
<?php echo CHtml::activeFileField($model,'image',array('id'=>'primaryupload')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'UPLOAD' : 'UPLOAD',array('id'=>'submit','class'=>'btn')); ?>
<?php $this->endWidget(); ?>
Any help will be appreciated. Because i am really frusrated at this point.
If you are only new to Yii and not in PHP, than you may know that uploaded files goes via $_FILES global variable and not via $_POST global variable. So to get uploaded file, you use
$uploadedFile = CUploadedFile::getInstance($model, 'image');
So your final code looks like this:
$post = Yii::app()->request->getPost('Test');
if ($post) {
$model->attributes = $post;
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if ($uploadedFile) {
$imageName = date("Y_m_d_H_i_s").$uploadedFile->name;
$model->image = $imageName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$imageName );
}
}
I think you should use $_FILES['image'] instead of $model->image.
As an option, you can "hardcode" file attribute in your form. Just:
<input type="file" id="yourid" name="yourname" />
Then in YourController, where you are parsing your POST data you could directly access to $_FILES['yourname'].
Not an elegant way, but simple and fast.
P.S.: if you are using $this->beginWidget in your view, then you should add to parameters
$this->beginWidget('CActiveForm', array(
...
'htmlOptions'=>array(
'enctype'=>'multipart/form-data'
),
));

Upload pictures from Yii showing endWiget() error

Hi I also had a problem when try to upload picture using this method.
My Action/model:
class Image extends CActiveRecord
{
public $foto;
...
public function rules()
{
return array(
...
array('foto', 'file', 'types'=>'jpg, gif, png'),
...
);
}
}
My Controller:
class ImageController extends Controller
{
public function actionCreate()
{
$model=new Image;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$model->image=CUploadedFile::getInstance($model,'foto');
if($model->save())
$model->foto->saveAs('productimages');
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
}
My view:
<?php $form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
); ?>
<?php echo $form->labelEx($model, 'foto'); ?>
<?php echo $form->fileField($model, 'foto'); ?>
<?php echo $form->error($model, 'foto'); ?>
...
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
But when I run, two problems appeared:
Problem #1:
endWiget() call [SOLVED by Ivan Misic]
ImageController contains improperly nested widget tags in its view "/var/www/html/onlineshop-nimalogos/protected/views/image/_form.php". A CActiveForm widget does not have an endWidget() call.
Problem#2:
Since problem # 1 is solved, came with another problem, the image is not saving at my 'productimages' folder.
Please help me with the problem # 2. Many thanks..
You have somewhere opened redundant CActiveForm widget and you should look into views and partials.
Yii is generting three view files with gii, and these are:
create.php update.php
| |
| |
+-------+-------+
|
|
_form.php
create and update views are rendering the same partial _form, so you should look in all three to find redundant beginWidget call.
The view you supported in your question should be _form.php partial view.

Yii CMultiFileUpload select multiple files

Got The Answer
To upload multiple file in to the database for registration
have tried so many ways to make multiple file upload workable using CMultiFileUpload widget. Already, I have checked and followed below links-
http://www.yiiframework.com/forum/index.php/topic/47665-multiple-file-upload/
Yii multiple file upload
BUT still no luck!!
Error: storing the data but the files are not getting uploaded
please help
Here is my code:
In Form
<?php $this->widget('CMultiFileUpload',
array(
'model'=>$model,
'attribute' => 'documents',
'accept'=>'jpg|gif|png|doc|docx|pdf',
'denied'=>'Only doc,docx,pdf and txt are allowed',
'max'=>4,
'remove'=>'[x]',
'duplicate'=>'Already Selected',
)
);?>
Controller Code
public function actionRegistration()
{
$model=new PatientRegistration;
$this->performAjaxValidation($model);
if(isset($_POST['PatientRegistration']))
{
$model->attributes=$_POST['PatientRegistration'];
if($model->validate())
{
if(isset($_POST['PatientRegistration']))
{
if($filez=$this->uploadMultifile($model,'documents','/Images/'))
{
$model->documents=implode(",", $filez);
}
$model->attributes=$_POST['PatientRegistration'];
if($model->save())
{
// $this->render('registration',array('model'=>$model));
$this->redirect(array('/patientregistration/patientview','id'=>$model->register_id));
}
}
}
}
$this->render('registration',array('model'=>$model));
}
public function uploadMultifile($model,$attr,$path)
{
/*
* path when uploads folder is on site root.
* $path='/uploads/doc/'
*/
if($sfile=CUploadedFile::getInstances($model, $attr)){
foreach ($sfile as $i=>$file){
// $formatName=time().$i.'.'.$file->getExtensionName();
$fileName = "{$sfile[$i]}";
$formatName=time().$i.'_'.$fileName;
$file->saveAs(Yii::app()->basePath.$path.$formatName);
$ffile[$i]=$formatName;
}
return ($ffile);
}
}
Add in CActiveForm widget
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
Hence u can use this code to upload multiple files in yiiframework
Here is the simplest Code for Multiple File Upload in Yii Framework
code
In Controller
public function actionCreate()
{
$model = new Upload;
echo Yii::app()->basePath.'/Images/';
if(isset($_POST['Upload']))
{
if($filez=$this->uploadMultifile($model,'Document','/Images/'))
{
$model->Document=implode(",", $filez);
}
$model->attributes=$_POST['Upload'];
if ($model->save())
{
$this->redirect(array('view', 'id' => $model->idUpload));
}
}
$this->render('create', array(
'model' => $model,
));
}
//Function for uploading and saving Multiple files
public function uploadMultifile ($model,$attr,$path)
{
/*
* path when uploads folder is on site root.
* $path='/uploads/doc/'
*/
if($sfile=CUploadedFile::getInstances($model, $attr)){
foreach ($sfile as $i=>$file){
// $formatName=time().$i.'.'.$file->getExtensionName();
$fileName = "{$sfile[$i]}";
$formatName=time().$i.'_'.$fileName;
$file->saveAs(Yii::app()->basePath.$path.$formatName);
$ffile[$i]=$formatName;
}
return ($ffile);
}
}
In Form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'upload-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<?php $this->widget('CMultiFileUpload',
array(
'model'=>$model,
'attribute' => 'Document',
'accept'=>'jpg|gif|png|doc|docx|pdf',
'denied'=>'Only doc,docx,pdf and txt are allowed',
'max'=>4,
'remove'=>'[x]',
'duplicate'=>'Already Selected',
)
);?>
That was all up is for multiple upload - that's nice, but as for multiple select you can try this yii extension
I hope that this link will help someone, because I was struggling with multiple select files for multiple upload then. Spent lot of time in Google search. Cheers

YII file upload not working

Hi I am attempting to upload a file and write it to the database using YII, but nothing is happening at all, Its neither saving the file nor name saving to DB.
My View...
<div class="row">
<div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
<div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
<div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>
My Model for validation...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//more rules
array('slider_image', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),
//more rules
);
}
Controller:
public function actionEdit()
{
$id = Yii::app()->getRequest()->getQuery('id');
$model = CustomPage::model()->findByPk($id);
if (!($model instanceof CustomPage))
{
Yii::app()->user->setFlash('error',"Invalid Custom Page");
$this->redirect($this->createUrl("custompage/index"));
}
if(isset($_POST['CustomPage']))
{
$model->attributes = $_POST['CustomPage'];
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image=CUploadedFile::getInstance($model,'slider_image');
}
if ($model->validate())
{
if ($model->deleteMe)
{
$model->delete();
Yii::app()->user->setFlash('info',"Custom page has been deleted");
$this->redirect($this->createUrl("custompage/index"));
}
else {
$model->request_url = _xls_seo_url($model->title);
if (!$model->save())
Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
else
{
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image->saveAs(Yii::app()->baseUrl.'images/'.$model->slider_image);
}
Yii::app()->user->setFlash('success',
Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y h:i:sa"))));
$this->beforeAction('edit'); //In case we renamed one and we want to update menu
}
}
}
}
$this->render('edit',array('model'=>$model));
}
I attempted to die; after if (CUploadedFile::getInstance($model,'slider_image')) and nothing is happening, so it seems its not recognising it at all.
Thank you.
I think you're missing a minor directive in your view
Check to confirm that your form tag has the attribute "enctype"
i.e. <form action="" method="post" enctype="multipart/form-data">...</form>
TO set this in CActiveForm, do:
<?php $form = $this->widget('CActiveForm', array(
'htmlOptions'=>array('enctype'=>'multipart/form-data')
));?>

YII file upload not adding to database using form

Im attempting to add a file upload field to a form in YII, while its succesfully submitting and uploading the file to the correct folder, its not adding anything to the database.
Im only learning this platform so any guidance would be great.
Here is my view...
<div class="row">
<div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
<div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
<div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>
Here is my controller...
public function actionEdit() {
$id = Yii::app()->getRequest()->getQuery('id');
$model = CustomPage::model()->findByPk($id);
if (!($model instanceof CustomPage)) {
Yii::app()->user->setFlash('error',"Invalid Custom Page");
$this->redirect($this->createUrl("custompage/index"));
}
if(isset($_POST['CustomPage'])) {
$model->attributes = $_POST['CustomPage'];
$model->image=CUploadedFile::getInstance($model,'slider_image');
if ($model->validate()) {
if ($model->deleteMe) {
$model->delete();
Yii::app()->user->setFlash('info',"Custom page has been deleted");
$this->redirect($this->createUrl("custompage/index"));
} else {
$model->request_url = _xls_seo_url($model->title);
if (!$model->save()) {
Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
} else {
$model->image->saveAs(Yii::app()->baseUrl.'images/'.$model->image);
Yii::app()->user->setFlash('success',
Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y h:i:sa"))));
$this->beforeAction('edit'); //In case we renamed one and we want to update menu
}
}
}
}
}
and my model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
// other rules
array('slider_image', 'file', 'types'=>'jpg, gif, png'),
);
}
The form itself overall is working fine, unfortunately I dont understand how YII adds to the database
Thanks
Adrian
EDIT: Ive also obviously got a slider_image field in that table
What your Controller code would do is save the file name of the upoloaded file in your database table. Another thing is: your code:
$model->image=CUploadedFile::getInstance($model,'slider_image');
is referring to the wrong attribute. I think it should be:
$model->slider_image=CUploadedFile::getInstance($model,'slider_image');
Finally, you need to call $model->slider_image->save('path.to.file'); in order to save the file to disk
I believe you get stock at $model->validate(). Because you do copy image above this line copying is fine but you do not go through validation so it never saves to DB.
var_dump($model->validate()); to see what is going on...

Categories