[SOLVED !!] Upload file to database

Hi

I’ve been searching through forums (“file upload”, “upload”, “blob”) but haven’t found the solution. I also tried to implement solution by quiang’s Wiki Tutorial http://www.yiiframew…-using-a-model/ without success.

I want to upload file to blob column in mysql5.

In view I have:




<div class="row">

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

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

<?php echo CHtml::endForm(); ?>

</div>	



‘cv_file_name’ is input for file browsing, and file input is done by CHtml::activeFileField as said in Wiki…

In model I have:




<?php


class Candidate extends CActiveRecord

{

public $uploaded_file;

.....

.....

public function rules()

{

array('cv_file_name', 'file', 'allowEmpty'=>false),

}

?>



In Controller I have:




public function actionCreate()

{

$model=new Candidate;


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

	{

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

  

                //some diagnostic stuff

		echo '<pre>'.$model->cv_file_name.'<br>';

		echo '<pre>blahblahblah<br>';	

                //some diagnostic stuff

	

		$uploaded_file = CUploadedFile::getInstance($model,'cv_file_name');


                //some diagnostic stuff to see if $file exists

		echo '<pre>echo file here: '.$file.' :echo file here<br>';

                //some diagnostic stuff to see if $file exists


		$model->cv_file_name=$uploaded_file->name;

		$model->cv_file_type=$uploaded_file->type;

		$model->cv_file_size=$uploaded_file->size;

		$model->cv_file_content=file_get_contents($uploaded_file->getTempName());

	

        	if($model->save())

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

	}


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

		'model'=>$model,

		));

}



I put some diagnostic messages there…

And I get:

/protected/controllers/CandidateController.php on line 81

This line: $model->cv_file_content=file_get_contents($uploaded_file->getTempName());

[color="#ff0000"]Please[/color], I have been messing with this stuff… ehhhhhh, toooooo long.

While this probably isn’t the ideal solution, I have it in a snippet and re-use it often. For your case replace ‘image’ with ‘cv_file_name’;

View _form.php:




<div class="row">

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

    <?php echo $form->fileField($model,'image'); ?>

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

</div> 



Controller create or update code placed just before $model->attributes=$_POST[‘modelName’];:




...

if (isset($_FILES['modelName']['size']['image']) && $_FILES['modelName']['size']['image'] > 0)

{

    $_POST['modelName']['fileName'] = $_FILES['modelName']['name']['image'];

    $_POST['modelName']['fileType'] = $_FILES['modelName']['type']['image'];

    $_POST['modelName']['fileSize'] = $_FILES['modelName']['size']['image'];

    $tmp_name = $_FILES['modelName']['tmp_name']['image'];

                

    $fp = fopen($tmp_name, 'r');

    $_POST['modelName']['image'] = fread($fp, filesize($tmp_name));

    fclose($fp);

}

...



Hi,

I used your code and now I don’t get error that trying to work on non-object, but now I get that my cv_file_name (input for file) is blank. No matter if I use:




echo $form->fileField($model,'cv_file_name'); ?>



or:




echo CHtml::activeFileField($model, 'cv_file_name'); ?>



If I comment rule in my model:




array('cv_file_name', 'file', 'allowEmpty'=>false),



I also added to my form definition enctype html option:




<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'candidate-form',

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

..................



I don’t get this error but file is not saved to database. What is goin’ on? :unsure:

You can also use CUploadedFile.

Well I tried CUploadedFile (see my first post) and without success.

Nobody ever tried file uploading to db using yii?

Sorry, I didn’t read carefully.

I tried lot of time ago (still was Yii 1.0) and I did everithing in the model.

I added a property to be set with CFileUpload, and I change the class like that:


<?php

class photograph extends CActiveRecord

{

        /* property for receive the new file*/		

	public $preview;


	/**

	 *saves the data and the type of the uploaded image

	 */

	public function beforeSave()

	{

		if($file=CUploadedFile::getInstance($this,'preview'))

		{

			$this->preview_data=file_get_contents($file->tempName);

			$this->preview_mime=$file->type;

			$this->resizeImage();

		}

		return parent::beforeSave();;

	}


	

}



This works, I hope it helps…

Here:




/* property for receive the new file*/          

public $preview;



this property $preview should be the name of input field on my form? ("cv_input file")

and here:




if($file=CUploadedFile::getInstance($this,'preview'))



‘preview’ is also name of form field in which I choose file from local disk?

?

WORKS !!

Code in view:




<div class="row">

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

<?php echo $form->fileField($model,'cv_file_name'); ?>

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

</div> 



Field on form:

Code in model:




class Candidate extends CActiveRecord

{

	

/* PROPERTY FOR RECEIVING THE FILE FROM FORM*/     	

public $cv_file_name;

/* MUST BE THE SAME AS FORM INPUT FIELD NAME*/     	


/**

*saves the name, size ,type and data of the uploaded file

*/

public function beforeSave()

{

if($file=CUploadedFile::getInstance($this,'cv_file_name'))

{


$this->cv_file_name=$file->name;

$this->cv_file_type=$file->type;

$this->cv_file_size=$file->size;

$this->cv_file_content=file_get_contents($file->tempName);


}


return parent::beforeSave();;


}



File data is properly uploaded to blob, name, size and type to appropriate columns.

Screenshot of phpMyAdmin:

Hope it helps someone else.

[color="#000080"]Thanks![/color]

Hurra!!

The next time I will first upload code and then speaking.

A chunk of code says more that 1000 words…

Anyway is better to use a property for get the image that has a different name than the database field. Rename in uploadedFile for example:




<div class="row">

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

<?php echo $form->fileField($model,'uploadedFile'); ?>

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

</div> 






class Candidate extends CActiveRecord

{

        

/* PROPERTY FOR RECEIVING THE FILE FROM FORM*/          

public $uploadedFile;

/* MUST BE THE SAME AS FORM INPUT FIELD NAME*/          


/**

*saves the name, size ,type and data of the uploaded file

*/

public function beforeSave()

{

if($file=CUploadedFile::getInstance($this,'uploadedFile'))

{


$this->cv_file_name=$file->name;

$this->cv_file_type=$file->type;

$this->cv_file_size=$file->size;

$this->cv_file_content=file_get_contents($file->tempName);


}


return parent::beforeSave();;


}




Also I had to change blob to mediumblob, because blob truncated file to 64kB.

Well it’s nice to have this solution - how about putting this in Wiki (there is on tutorial, but about uploading file to filesystem) - who should I contact in this case?

Now I am working on displaying link to the blob’ed file and open it onClick(). Have done it once but in pure PHP, not in Yii, this is my next milestone.

I think that I will do such a wiki.

You can create as wiki as you wish with your forum account, no needs to contact anyone.

Ok, I did the wiki.

There is a sample even for showing/dowloading the file.

[color="#FF0000"]G[/color][color="#0000FF"]r[/color][color="#006400"]e[/color][color="#9932CC"]a[/color][color="#A0522D"]t[/color] [color="#FF0000"]j[/color][color="#0000FF"]o[/color][color="#006400"]b[/color]! ::)

How’s controller??

Look @ the wiki. In controller you define action to show/retrieve saved file.

As said pc131, follow the wiki and if you find something incorrect, please say us so we can correct the wiki (or correct you immediatly if you are sure)

sorry i dnt understand… i just need to upload a file and save path to database and file to a root folder…

sorry i dnt understand… i just need to upload a file and save path to database and file to a root folder…

Well this topic, and corresponding wiki concerns uploading file [color="#0000FF"]to database[/color], [color="#FF0000"]not filesystem[/color].

Maybe this wiki can help you.

no, i tried that…its not working…thats the problem and i m here in this discussion …

Sorry for asking (maybe little bit out of topic) but why you chosen, not to store files in database? It is easier to maintain and backup.