无法使用Yii将文件上传到服务器

时间:2014-01-21 06:20:39

标签: php mysql database yii

我正在构建一个YII Web应用程序,我正在尝试添加一个用户可以将照片上传到Web应用程序的功能。我已经搜索了有关如何执行此操作的教程或文档,但没有取得成功。

我被告知最简单的方法是将实际图像存储在平面文件中的服务器上,然后将路径存储到数据库中的图像中。我创建了名为Pictures的模型,其中包含以下属性:Titleurl和& description

以下是我的控制器中的创建操作:

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

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

    if(isset($_POST['Pictures']))
    {
        $model->attributes=$_POST['Pictures'];
        $uploadedFile=CUploadedFile::getInstance($model,'url');
        if($model->save())
            $uploadedFile->saveAs(Yii::app()->basePath.'/granados/images/testimage.jpg');
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

这是我的表格:

    <?php
/* @var $this PicturesController */
/* @var $model Pictures */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'pictures-form',
    'htmlOptions' => array(
        'enctype' => 'multipart/form-data',
    ),
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>false,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'title'); ?>
        <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>128)); ?>
        <?php echo $form->error($model,'title'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'url'); ?>
        <?php echo CHtml::activeFileField($model, 'url'); ?>
        <?php echo $form->error($model,'url'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'description'); ?>
        <?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
        <?php echo $form->error($model,'description'); ?>
    </div>

    <div class="row buttons">
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

这是我的模特:

    <?php

/**
 * This is the model class for table "{{pictures}}".
 *
 * The followings are the available columns in table '{{pictures}}':
 * @property integer $id
 * @property string $title
 * @property string $url
 * @property string $description
 */
class Pictures extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{pictures}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, url', 'required'),
            array('description', 'length', 'max'=>500),
            array('url', 'file','types'=>'jpg, gif, png'), 
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, title, url, description', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'url' => 'Url',
            'description' => 'Description',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('url',$this->url,true);
        $criteria->compare('description',$this->description,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Pictures the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

如果有人能指出我正确的方向,那就太好了。此时,我无法上传任何内容。当我提交新表单时,我收到404错误。

我现在完全迷失了,不知道该怎么做。以下是我到目前为止尝试过的链接:

http://stackoverflow.com/questions/3607200/file-upload-with-yiis-activeform

http://stackoverflow.com/questions/10348887/show-uploaded-image-yii

http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

1 个答案:

答案 0 :(得分:2)

试试这段代码。

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

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

    if(isset($_POST['Pictures']))
    {
        $model->attributes=$_POST['Pictures'];
        $model->url = CUploadedFile::getInstance($model,'url');
        if($model->save()) {        
            $fullImgSource = Yii::getPathOfAlias('webroot').'/granados/images/'.$model->url;
            $model->url->saveAs($fullImgSource);
            $this->redirect(array('view','id'=>$model->id));    
        }   
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

希望它会对你有所帮助。

由于

改进:if语句后缺少阻止。