我使用CUploadedFile
在我的网络应用程序中上传多个文件。我为此目的使用了以下代码:
public function actionCreate(){
$model=new Status();
$this->performAjaxValidation($model);
if(isset($_POST['Status']))
{
$model->attributes=$_POST['Status'];
Yii::log("actionCreate actionCreate inside if" .isset($_POST['Status']));
$images = CUploadedFile::getInstancesByName('description');
if(isset($images) && count($images)> 0)
{
foreach ($images as $image=>$pic)
{
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/uploads/'.$pic->name,0777))
{
$model= new Status();
$model->description =$pic->name;
$url = Yii::getPathOfAlias('webroot').'/uploads';
$model->insert();
}
}
$this->redirect(array('view','id'=>$model->status_id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
当我上传多个文件时,它会保存所有文件但使用不同的ID(PK)。我需要将所有上传的文件名保存到名为description
的一个字段中。我该怎么办?
答案 0 :(得分:0)
尝试这样做
public function actionCreate(){
$model=new Status();
$this->performAjaxValidation($model);
if(isset($_POST['Status']))
{
$model->attributes=$_POST['Status'];
Yii::log("actionCreate actionCreate inside if" .isset($_POST['Status']));
$images = CUploadedFile::getInstancesByName('description');
if(isset($images) && count($images)> 0)
{
// Create a blank array.
$pic_name = array();
foreach ($images as $image=>$pic)
{
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/uploads/'.$pic->name,0777))
{
//Put values in array.
$pic_name[$image] = $pic->name;
$url = Yii::getPathOfAlias('webroot').'/uploads';
}
}
// If array has multiple values i.e. more than zero then and only then save it in description as a string.
if(count($pic_name) > 0){
$_pics = implode('|',$pic_name);
// Do not create model everytime a new image is iterated
$model= new Status();
$model->description = $_pics;
$model->insert();
}
$this->redirect(array('view','id'=>$model->status_id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
我不知道循环中$ url的用途是什么,这就是我保持原样的原因。