【问题标题】:How to save the names of muliple uploaded files to one field in yii 1如何将多个上传文件的名称保存到yii 1中的一个字段
【发布时间】:2017-05-10 12:15:14
【问题描述】:

我使用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,
    ));
}

当我上传多个文件时,它会保存所有文件,但 ids(PK) 不同。我需要将所有上传的文件名保存到名为 description 的字段中。我该怎么做?

【问题讨论】:

  • 对不起,我不明白这个问题。 PK(主键)在这里做什么?你说的“场”是什么意思?
  • 现在当我看到第一个答案时,我现在明白你想要什么了。 :)

标签: php yii yii1.x


【解决方案1】:

试试这个方法

    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 有什么用,所以我一直保持原样。

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 1970-01-01
    • 2019-11-04
    • 2019-03-21
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多