编辑视图而不修改文件cakePHP

时间:2013-09-10 10:06:45

标签: php cakephp file-upload

查看(编辑)正确显示所有字段并更新已修改的字段但无法处理文件。即,如果上传新文件,则必须更新,如果不保留旧文件名。

控制器:

public function edit($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    $post = $this->Student->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }

    if ($this->request->is('post') || $this->request->is('put')) {
        $this->Student->id = $id;
        if ($this->Student->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been updated.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to update your post.'));
    }

    if (!$this->request->data) {
        $this->request->data = $post;
    }
    }

查看:

<h1>Edit student record</h1>
<?php   
    echo $this->Form->create('Student',array('type'=>'file'));
    echo $this->Form->input('first_name'); 
    echo $this->Form->input('current_address');
    echo 'resume'.$this->Form->file('resume');
    echo $this->Form->input ('comments');
    echo 'photo'.$this->Form->file('photo'); 
    echo $this->Form->input('id', array('type' => 'hidden'));
    //echo $this->Form->input('resume', array('type' => 'hidden'));
    //echo $this->Form->input('photo', array('type' => 'hidden'));
    echo $this->Form->end('Save Post');

有人可以建议我如何处理上传内容

1 个答案:

答案 0 :(得分:4)

检查简历,照片字段。如果它是空的,则取消设置变量。如果不为空 - 上传并移至目的地:

if (empty($this->request->data['Student']['resume']['name'])) {
    unset($this->request->data['Student']['resume']);
} else {
    $resume = $this->request->data['Student']['resume'];
    move_uploaded_file($resume['tmp_name'], 'newPath/' . $resume['name']);
    $this->request->data['Student']['resume'] = $resume['name'];
}

if (empty($this->request->data['Student']['photo']['name'])) {
    unset($this->request->data['Student']['photo']);
} else {
    $photo = $this->request->data['Student']['photo'];
    move_uploaded_file($photo['tmp_name'], 'newPath/' . $photo['name']);
    $this->request->data['Student']['photo'] = $photo['name'];
}