Uploading and Downloading files


(Coolsrikanth4u) #1

I have a form where I want to upload files. I followed the cookbook http://www.yiiframework.com/doc/cookbook/2/

I am getting error as Call to a member function saveAs() on a non-object.

doc_comment is the field I am using to upload.

Any help is appreciated.

Thnks.

My controller code is:




public function actioncreate()

{

Yii::app()->user->checkAccess('create');

$model=new documents;

if(isset($_POST['documents']))

{

$model->attributes=$_POST['documents'];

$model->doc_comment=CUploadedFile::getInstance($model,'doc_comment');


if($model->save())

{

$model->doc_comment->saveAs("C:/xampp/htdocs/new/images/");

$this->redirect(array('view','id'=>$model->document_id));

}

}


$this->render('create',array(

'model'=>$model,

));

}



And view is:




<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));?>


.

.

.

.

.


<?php echo $form->labelEx($model,'document comment'); ?>

<?php echo CHtml::activeFileField($model,'document'); ?>

<?php echo $form->error($model,'doc_comment'); ?>

.


.

.

.

<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>




(Support) #2

I am not sure that this will fix your problem but I believe you should also be passing the filename to the saveAs() function, not just the directory to save it in.

Try changing:




$model->doc_comment->saveAs("C:/xampp/htdocs/new/images/");



To:




$model->doc_comment->saveAs("C:/xampp/htdocs/new/images/" . $model->doc_comment);



I use code like this to allow admins to upload files for my users to access and it works as expected.

Also, try doing a var_dump($model->doc_comment) before the saveAs() call to make sure that $model->doc_comment is indeed being populated by CUploadedFile::getInstance()


(Coolsrikanth4u) #3

I tried using var_dump($model->doc_comment) and $model->doc_comment->saveAs("C:/xampp/htdocs/new/images/" . $model->doc_comment); then I got null followed by fatalerror: Call to a member function saveAs() on a non-object.

var_dump given me null.

The main reason is no file is been getting selected.

I made the field being required in model then it gave error as it cannot be blank.

Can anybody help me how to get rid of this error.

thanks.


(Mh) #4

You have a mismatch in attribute names:


$model->doc_comment=CUploadedFile::getInstance($model,'doc_comment');


...


<?php echo CHtml::activeFileField($model,'document'); ?>


(Coolsrikanth4u) #5

Thankyou very much mike,

That solved the problem(shame on me) of uploading the files to database.

But I couldnot find any relevant searches in Yii to create download links for the files from database. I am new to php and yii framework.

Any help is appreciated.

Thanks a lot for the support being given to newbies.


(Mh) #6

There are many ways to solve this. But it depends on your requirements. Some options:

  • Files are uploaded to a public folder in www: Then you only have to create a link with the filename from DB

  • Files are uploaded to a private directory: Then create a controller action for download. There you can check user permission and use readfile() to send the file to the client through PHP.


(Spyros) #7

Also check the CFile extension that has many methods for manipulating files


(Coolsrikanth4u) #8

thanks mike and spyros…that helped me a lot…

I want your help in another small problem regarding uploading files.

I have a form where there is a possibility to upload as many as 14 documents at a time. So I used batch update. The problem I am facing there is an error which says saveas calling non object( I got to know that error occurs if documents are not being read). When I tried with the single document(different code for single) then it worked fine.

This is my code for multiple documents…

view




<?php foreach($doc as $k=>$ment): ?>

<?php echo CHtml::activeDropDownList($ment,"[$i]doc_type_id",$ment->DocumentOptions,

              array('empty' => 'Select the document'));?>

<?php echo "comments".$form ->textField($ment,"[$i]doc_type_other_desc",array('size'=>20,'maxlength'=>30)); ?>

  <?php echo "upload document".CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>

		<?php echo CHtml::activeFileField($ment,"[$i]document"); ?>

<?php echo $form->error($ment,"[$i]document"); ?>

<br/>

<?php endforeach; ?>



Controller:




 if(isset($_POST['documents']))

		         {

                            $valid=true;

                              foreach($doc as $m=>$abc)

                              {

                                   if(isset($_POST['documents'][$m]))

 {

   $doc[$m]->attributes=$_POST['documents'][$m];

   $doc[$m]->document = CUploadedFile::getInstance($doc[$m], "[$m]document" );

 }

 $valid=$valid && $doc[$m]->validate();

 }

if($valid)

 {

              foreach($doc as $m=>$abc)

                {

       $abc->student_id = $student_id->student_id;   

 $abc->document->saveAs('C:/xampp/htdocs/new/images/'.$abc->document->getName());

        $abc->save(false);

                }

      $this->redirect(array("apps/successful"));

 }

 

I followed cookbook http://www.yiiframework.com/doc/cookbook/29/

please let me know where I am going wrong.

Thanks a lot … :)


(Coolsrikanth4u) #9

Please help me. Any help is appreciated.


(Nirmal Websanjal) #10

Hi I also got error wile uploading image

my update action is here


public function actionUpdate($id)

	{

		$model=$this->loadModel($id);

		

		$img_flyer = CUploadedFile::getInstance($model,'image');

		if ((is_object($img_flyer) && get_class($img_flyer)==='CUploadedFile'))

			$model->image = $img_flyer;

		

		


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Job']))

		{

		 

			

			

			$model->attributes=$_POST['Job'];

			foreach ($_POST['Job'] as $key=>$value)

				$model->$key=$value;

			if($model->validate()){

				$model->save(false);

				$contractor = $model->contractor;

				$contractor->contact_id = Main::saveContact($model);

				$contractor->address_id = Main::saveAddress($model);

				

				if (is_object($img_flyer))

				{

					print_r($img_flyer); 

					$id = $contractor->image_id;

					

					$img_flyer="img_contractor_".$id.".".findFileExt($img_flyer);

					

					//$img_flyer = strtolower($img_flyer);

					// $fileDir = dirname(Yii::app()->basePath).'/images/contractor/'.$img_flyer; 

					 $model->image->saveAs("D:/xampp/htdocs/contractorgig/images/contractor/orginal/" .$img_flyer);

				

					$width = array('1'=>'48','2'=>'240');

					$height = array('1'=>'60','2'=>'300');

				

					$fileDir1 = dirname(Yii::app()->basePath).'/images/contractor/thumbs/big/'.$img_flyer;

					$fileDir2 = dirname(Yii::app()->basePath).'/images/contractor/thumbs/small/'.$img_flyer;

					for($i=1;$i<=2;$i++):

					@copy($fileDir,$fileDir.$i);

					$image = Yii::app()->image->load($fileDir.$i);

					$image->resize($width[$i],$height[$i],IMAGE::AUTO);

					$image->save();

					endfor;

					$img = Image::model()->findByPk($id);

					$img->name = $img_flyer;

					$img->save(false);

				}

				



my file upload form file with is


<div class="cf mt-20">

			<label for="company_logo" class="col-l tg-label bold">Logo</label>

			<?php echo CHtml::activeFileField($model,'image',array('size'=>40,'maxlength'=>255,'class'=>"ml-45")); ?>

			<p class="gra mt-8 clear ml-75">

				Optional - Your company logo will appear at the top of your listing.

				190px wide is optimal. We'll resize automatically if it's wider than

				190px.<br />The following image file formats are supported only:

				JPEG, GIF, PNG

			</p>

		</div>

I has also set


'htmlOptions'=>array('enctype'=>'multipart/form-data','onclick'=>'job_form_valid();'),

I had also defined

public $image in Job model

Also when print_r I got the object too

but I can’t get it saved the error with debug the file is


CUploadedFile Object ( [_name:CUploadedFile:private] => ico1.png [_tempName:CUploadedFile:private] => D:\xampp\tmp\php82A8.tmp [_type:CUploadedFile:private] => image/png [_size:CUploadedFile:private] => 5410 [_error:CUploadedFile:private] => 0 [_e:CComponent:private] => [_m:CComponent:private] => )

Fatal error: Call to a member function saveAs() on a non-object in D:\xampp\htdocs\contractorgig\protected\controllers\JobController.php on line 167

Please help me out in this as soon as possible. Thank you