Yii Framework Forum: Загрузка Файла Проблема С Загрузкой Файла - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Загрузка Файла Проблема С Загрузкой Файла Rate Topic: -----

#1 User is offline   KIN1991 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 6
  • Joined: 09-January 13

Posted 09 January 2013 - 11:53 PM

Люди помогите разобраться с загрузкой файла на сервак, при загрузке в форму и отправке постоянно сообщается ошибка что форма с файлом пуста

Вот что я написал
Контроллер
public function actionCreate()
    {
        $model=new students;
        $this->performAjaxValidation($model);
        if(isset($_POST['Students']))
        {
            $model->attributes=$_POST['Students'];
            $model->image=$this->saveFile($model,'image');
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
    public function actionUpdate()
    {
        $model=$this->loadModel();
        
        $this->performAjaxValidation($model);

        if(isset($_POST['Students']))
        {
            $model->attributes=$_POST['Students'];
            $model->image=$this->saveFile($model,'image');
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }
    
    public function saveFile($model,$name=null){
        $tmp=$_POST[$name.'-src'];
        $delete=true;
        if($name!==null){
            $UPimage=CUploadedFile::getInstance($model,$name);
            if($UPimage!==NULL) {
                if(Students::model()->count("`{$name}`='{$tmp}'")>0){$delete=false;}
                if(strstr($UPimage->type,'image')) {
                    $path=pathinfo($UPimage->name);
                    $fileName='Students-'.time().'.'.$path["extension"];                    
                    $UPimage->saveAs('upload/tmp_Students_'.$fileName); // save the uploaded file
                    Yii::import('application.extensions.image.Image');
                    $image = new Image('upload/tmp_Students_'.$fileName);
        $w=$image->width;$h=$image->height;
         if($w>306 || $h>306)
        $image->resize(306,306);
        $image->save('upload/Students/'.$fileName);
         if($delete){if(is_file('upload/Students/'.$tmp))unlink('upload/Students/'.$tmp);}

         if($w>100 || $h>100)
        $image->resize(100,100);
        $image->save('upload/Students/sm/'.$fileName);
         if($delete){if(is_file('upload/Students/sm/'.$tmp))unlink('upload/Students/sm/'.$tmp);}
                    unlink('upload/tmp_Students_'.$fileName);
                }else {
                    if($delete){if(is_file('upload/Students/'.$tmp))unlink('upload/Students/'.$tmp);}
                    $UPimage->saveAs('upload/Students/'.$fileName); // save the uploaded file
                }
                return $fileName;
            }elseif($_POST[$name.'-src']!=''){
                return $_POST[$name.'-src'];
            }
        }
        return $tmp;
    }



Модуль
/**
 * This is the model class for table "data_students".
 */
class Students extends CActiveRecord
{
    /**
     * The followings are the available columns in table 'data_students':
     * @var integer $id
     * @var string $title
     * @var string $image
     */

    /**
     * Returns the static model of the specified AR class.
     * @return Students the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'data_students';
    }

    public function modelTitle()
    {
        return 'Students';
    }


    public function modelOptions()
    {
        return array(
            'images'=>array(
                'sm'=>'100x100',
                'full'=>'500x500'
            )
        );
    }
    /**
     * @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, image', 'required'),
            array('title, image', 'length', 'max'=>255, 'encoding' => 'UTF-8'),
            array('image', 'file','types'=>'jpg, png, gif','allowEmpty'=>true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, image', '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(
        );
    }
    public function relationsTitle()
    {
        return array(
            );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => '№',
            'title' => 'Название',
            'image' => 'Изображение',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: 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);
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
        ));
    }

    public function beforeValidate() {
        return true;
    }
        }

 


Сама форма
<div class="row" >
        <?php echo $form->labelEx($model,'image'); ?>
        <?php echo $form->fileField($model,'image'); ?>
        <?php echo $form->error($model,'image'); ?>
        <?php echo is_file('upload/Students/sm/'.$model->image.'')?'<div class="picture">'.CHtml::link(CHtml::image('/upload/Students/sm/'.$model->image),'/upload/Students/'.$model->image,array('target'=>'_blank')).'</div>':''; ?>
    <?php echo is_file('upload/Students/'.$model->image)?CHtml::hiddenField('image-src',$model->image):''; ?>

    </div>



помогите пожалуйста а то я уже не знаю что и делать
0

#2 User is offline   Зверь 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 13
  • Joined: 08-January 13
  • Location:Екатеринбург

Posted 10 January 2013 - 12:09 AM

А вы посмотрели html-исходник страницы c формой. Форма правильная сделана, с параметром enctype="multipart/form-data" ?
0

#3 User is offline   KIN1991 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 6
  • Joined: 09-January 13

Posted 10 January 2013 - 12:13 AM

View PostЗверь, on 10 January 2013 - 12:09 AM, said:

А вы посмотрели html-исходник страницы c формой. Форма правильная сделана, с параметром enctype="multipart/form-data" ?

Да вот я определил там этот параметр
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'Students-form',
	'enableAjaxValidation'=>true,
	'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); 
?>

0

#4 User is offline   Зверь 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 13
  • Joined: 08-January 13
  • Location:Екатеринбург

Posted 10 January 2013 - 12:29 AM

Еще так при поверхностном осмотре смущает проверка полей в модели

View PostKIN1991, on 09 January 2013 - 11:53 PM, said:

Модуль
class Students extends CActiveRecord
{
...
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, image', 'required'),
            array('title, image', 'length', 'max'=>255, 'encoding' => 'UTF-8'),
            array('image', 'file','types'=>'jpg, png, gif','allowEmpty'=>true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, image', 'safe', 'on'=>'search'),
        );
    }
...



array('title, image', 'length', 'max'=>255, 'encoding' => 'UTF-8'),


может фрейворк ругается на поле image, предпологая его текстовым полем в 255 символов, может image убрать из этой проверки?
1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users