caly
(Calypsogurl)
July 28, 2009, 1:56am
1
I’m using this code to upload files to the database, while all the attributes are correct, the actual file doesn’t seem to upload correctly.
public function actionCreate()
{
$model=new Report;
if(isset($_POST['Report']))
{
$file = CUploadedFile::getInstance($model,'data');
$model->name=$file->name;
$model->type=$file->type;
$model->size=$file->size;
$model->data=$file;
if($model->save()) {
$this->redirect(array('show','id'=>$model->id));
}
}
$this->render('create',array('model'=>$model));
}
Example, instead of seeing this in the database table:
app.txt text/plain 1496 [BLOB - 1.5 KiB]
I see this:
app.txt text/plain 1496 [BLOB - 7 B]
Anyone know why?
Thanks!
Hello caly,
your problem is in this line:
$model->data=$file;
$file is an instance of CUploadedFile and contains some information about uploaded file but doesn’t return the uploaded file contents. You need different approach to save file to DB.
You should use a php function like file_get_contents() to read file contents. http://pl2.php.net/file_get_contents
The best option IMO is to go like that:
$file = CUploadedFile::getInstance($model,'data');
if(!$file->getHasError()){
$model->name=$file->name;
$model->type=$file->type;
$model->size=$file->size;
$model->data=file_get_contents($file->getTempName());
}
I hope that helps .
knut
(Knut Urdalen)
July 28, 2009, 6:21am
3
You should check for file upload errors with CUploadedFile::getHasError() and CUploadedFile::getError() before saving your record to avoid broken uploads.
caly
(Calypsogurl)
July 29, 2009, 1:14am
4
Thank you both! With the added error check and file_get_contents call, the files upload perfectly now.
andrwsv
(Andresvillegass)
August 29, 2011, 3:30pm
5
in this line
$file = CUploadedFile::getInstance($model,‘data’);
data is refer to this line in the model:
array(‘data’, ‘file’, ‘types’=>‘jpg, gif, png’),
or is the variable define in the model "public $data" ??
I try this example but don’t work, do you helpme ??