I’m triying to upload images with the TbFileUpload widget following this wiki how-to-tbfileupload but when I put the widget in my view and click the add files button, shows me a window to select the image, but when I select the image, nothing happens… I’m not quite sure if this widget show something like this example http://blueimp.github.io/jQuery-File-Upload/ when I select the image, shows me the image and the name of the file…
I’m really lost in this, any help would be appreciated.
I’m using a public variable in the controller named $imageName, to obtain the name of the picture in the action upload function of the wiki, and in that function $imageName works and have value ($this->imageName) but when I want to use this public variable in my actionCreate function, it seems that lost the value!
class MyModel extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
public $imageName;
public function actionUpload()
{
header('Vary: Accept');
if (isset($_SERVER['HTTP_ACCEPT']) &&
(strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false))
{
header('Content-type: application/json');
} else {
header('Content-type: text/plain');
}
$data = array();
$model = new MyModel('upload');
$model->picture = CUploadedFile::getInstance($model, 'picture');
if ($model->picture !== null && $model->validate(array('picture')))
{
$model->picture->saveAs(
Yii::getPathOfAlias('webroot.images').'/'.$model->picture->name);
$this->imageName = $model->picture->name;
// if($model->save()){
$data[] = array(
// 'name' => $model->picture->name, Use the public variable instead
'name' => $this->imageName,
'type' => $model->picture->type,
'size' => $model->picture->size,
// we need to return the place where our image has been saved
'url' => 'http://phantom/application/images/'.$model->picture->name);
// Yii::getPathOfAlias('fileupload.url').'/'.$model->picture->name);
// );
// } else {
// $data[] = array('error' => 'Model not saved');
// }
} else {
if ($model->hasErrors('picture'))
{
$data[] = array('error', $model->getErrors('picture'));
} else {
throw new CHttpException(500, "Could not upload file ". CHtml::errorSummary($model));
}
}
// JQuery File Upload expects JSON data
echo json_encode($data);
}
the code of the actionCreate is
public function actionCreate()
{
$model=new MyModel;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['MyModel']))
{
$model->attributes=$_POST['MyModel'];
//Use the name obtained in actionUpload
$model->pictureName = $this->imageName;
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}