如何使用yii中的路径将文件上传到mysql表

时间:2014-07-23 14:05:07

标签: php mysql sql yii

我尝试将文件上传到MySQL表,但它不起作用。 这就是我写的:

视图:

<div class="row">
    <?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
    <?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
    <?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>

模型: 我添加了这个属性:

public $doc_ordered_recieved;

这个冲动:

array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'update'),

控制器:

public function actionCreate()
    {
        $model=new Orders;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Orders']))
        {

            $model->attributes=$_POST['Orders'];
            $model->doc_ordered_recieved=CUploadedFile::getInstance($model,'doc_ordered_recieved');
            if($model->save())
            {
                $doc_ordered_recieved->saveAs('http://localhost/files');
                $this->redirect(array('view','id'=>$model->oid));
            }
        }
    $this->render('create',array('model'=>$model,
        ));
    }
请帮助我,我不知道为什么它不起作用????

谢谢大家 利耶

2 个答案:

答案 0 :(得分:0)

只需查看代码,我就可以看到您需要从

更改文件路径
$doc_ordered_recieved->saveAs('http://localhost/files');

$doc_ordered_recieved->saveAs(Yii::app()->basePath.'path/to/localFile');

此外,您应该提供有关您的模型的更多信息。

答案 1 :(得分:0)

首先,您需要更改规则以添加创建方案:

array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),

并且在您的控制器的创建操作中,您需要执行以下操作:

public function actionCreate()
{
    $model=new Orders;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Orders']))
    {

        $model->attributes=$_POST['Orders'];
        $uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
        if($model->save())
        {
            if(!empty($uploadedFile))  // check if uploaded file is set or not
            {

                if($model->image == null || empty($model->image)){
                    $rnd = rand(0,9999);// generate random number between 0-9999
                    $fileName = "{$rnd}-{$uploadedFile}";
                    $model->image = $fileName;
                }
                $uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
                // redirect to success page
            }
            $this->redirect(array('view','id'=>$model->oid));
        }
    }
        $this->render('create',array('model'=>$model,
    ));
}