Store a local file in the database with ActiveRecord

Hello,

I am using EAjaxUpload to upload a file from my form. In my controller I have this:




    public function actionUploadPhoto() {


        //store file locally

        Yii::import("application.extensions.EAjaxUpload.qqFileUploader");


        $folder = Yii::getPathOfAlias('application') . '\upload\\';

        $allowedExtensions = array("jpg"); 

        $sizeLimit = 3 * 1024 * 1024; // maximum file size in bytes


        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

        $result = $uploader->handleUpload($folder);


        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);


        $fileSize = filesize($folder . $result['filename']); //GETTING FILE SIZE

        $fileName = $result['filename']; //GETTING FILE NAME



At this stage the file is successfully stored in the directory ‘upload’

Now I want to store the file in the database. My model is :




<?php


/**

 * This is the model class for table "tbl_file_content".

 *

 * The followings are the available columns in table 'tbl_file_content':

 * @property integer $id

 * @property string $name

 * @property string $type

 * @property integer $size

 * @property string $content

 */

class FileContent extends CActiveRecord

{

	public function rules()

	{

		return array(

			array('id, name, type, size, content', 'safe'),

		);

	}


 ... //generated code by gii - no custom logic

}



and my database table is




CREATE TABLE tbl_file_content(

  id INT(11) NOT NULL AUTO_INCREMENT,

  name VARCHAR(70) NOT NULL,

  type VARCHAR(50) NOT NULL,

  size INT(11) NOT NULL,

  content MEDIUMBLOB NOT NULL,

  PRIMARY KEY (id)

)



Now I want to read the local file, set the FileContent attributes and store it.




        $fullFileName = $folder . "\\" . $fileName;

        $content = file_get_contents($fullFileName);

   

        $fileContent = new FileContent();


        $fileContent->name = $fileName;

        $fileContent->type = 'application/octet-stream';

        $fileContent->size = $fileSize;

        $fileContent->content = $content;


        $errors = $fileContent->validate();

        

        $fileContent->save(false);




The validation works but then the "save" method crashes. It fails in the DB Insert and I get a strange error "MySQL server has gone away".

If I remove the line


$fileContent->content = $content; 

it works!

So there’s something wrong with my file stream. Any idea ?

Thanks

Renaud

By the way




$content = file_get_contents($fullFileName);



when I try to check the $content value in the debugger I can see it’s full of strange characters and often it will make NetBeans crash.

So I guess I need to convert this to a proper "character only" string. I am really not familiar with PHP IO…

did you check the size of the file how big the file is?