您好我正在使用XUpload在我的应用中上传照片,但是当它上传到相应的文件夹时,它无法保存到我的数据库中。下面是添加照片的代码。模型是Carousel。请帮忙。感谢。
public function afterSave()
{
$this->addImages();
parent::afterSave();
}
public function addImages()
{
//If we have pending images
if( Yii::app( )->user->hasState('carouselphoto') ) {
$userImages = Yii::app( )->user->getState('carouselphoto');
//Resolve the final path for our images
$path = Yii::app( )->getBasePath( )."/../images/uploads/{$this->id}/";
//Create the folder and give permissions if it doesnt exists
if( !is_dir( $path ) ) {
mkdir( $path );
chmod( $path, 0777 );
}
//Now lets create the corresponding models and move the files
foreach( $userImages as $image ) {
if( is_file( $image["path"] ) ) {
if( rename( $image["path"], $path.$image["filename"] ) ) {
chmod( $path.$image["filename"], 0777 );
$img = new Carousel();
$img->size = $image["size"];
$img->mime = $image["mime"];
$img->name = $image["name"];
$img->photo_name = "/images/uploads/{$this->id}/".$image["filename"];
$img->id = $this->id;
if( !$img->save( ) ) {
//Its always good to log something
Yii::log( "Could not save Image:\n".CVarDumper::dumpAsString(
$img->getErrors( ) ), CLogger::LEVEL_ERROR );
//this exception will rollback the transaction
throw new Exception( 'Could not save Image');
}
}
} else {
//You can also throw an execption here to rollback the transaction
Yii::log( $image["path"]." is not a file", CLogger::LEVEL_WARNING );
}
}
//Clear the user's session
Yii::app( )->user->setState( 'carouselphoto', null );
}
}
感谢乔米勒。这是我的访问规则代码段。但是,没有任何错误
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('photo_name', 'required'),
array('gallery_id', 'numerical', 'integerOnly'=>true),
array('photo_name, alt', 'length', 'max'=>256),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, photo_name, gallery_id, alt', 'safe', 'on'=>'search'),
array('photo_name', 'file', 'types' => 'jpg,jpeg,gif,png'),
);
}
这里是设置的位置(actionUpload)
//Now we need to save this path to the user's session
if( Yii::app( )->user->hasState('carouselphoto') ) {
$userImages = Yii::app()->user->getState('carouselphoto');
} else {
$userImages = array();
}
$userImages[] = array(
"path" => $path.$filename,
//the same file or a thumb version that you generated
//"thumb" => $path.$filename,
"filename" => $filename,
'size' => $model->size,
'mime' => $model->mime_type,
'name' => $model->name,
);
Yii::app( )->user->setState( 'carouselphoto', $userImages );
答案 0 :(得分:0)
我有同样的问题,你应该做的一件事就是调用if(!$ img-> save())@Joe Miller如何说你有一个递归。
我尝试在分配后打印$ img-> name = $ image ['name'],它确实有效。
但是这种变化没有反映在数据库领域..不知道为什么。
我打算这样试试:
if(Yii::app()->user->hasState('xuploadFiles' )) {
$this->addImages();
return true;
}parent::afterSave();
cuz可能会返回parent :: afterSave();总是返回false,所以它不会保存字段。 我不知道......我需要先检查一下。
对我来说这样工作:$ this-> saveAttributes(array('image_url'));
你应该试试它是否适合你。 $ this-> saveAttributes(array('size,mime,name,photo_name,id'));