图片无法上传cakephp 2.0

时间:2013-12-10 10:02:59

标签: cakephp

我使用了一个组件上传图片,添加组件后控制器没有问题。这是代码

class OesUsersController extends AppController {

var $helpers = array('Html', 'Form');
var $components = array('upload');

public function index() {
}

public function upload() 
{

    if (empty($this->data)) 
    {
        $this->render();
    }
    else 
    {
        $this->cleanUpFields();

        // set the upload destination folder
        $destination = realpath('../../app/webroot/img/uploads/') . '/';

        // grab the file
        $file = $this->data['Image']['filedata'];

        // upload the image using the upload component
        $result = $this->Upload->upload($file, $destination, null, array('type' => 'resizecrop', 'size' => array('400', '300'), 'output' => 'jpg'));

        if (!$result){
            $this->data['Image']['filedata'] = $this->Upload->result;
        } else {
            // display error
            $errors = $this->Upload->errors;

            // piece together errors
            if(is_array($errors)){ $errors = implode("<br />",$errors); }

            $this->Session->setFlash($errors);
            $this->redirect('/images/upload');
            exit();
        }
        if ($this->Image->save($this->data)) {
            $this->Session->setFlash('Image has been added.');
            $this->redirect('/images/index');
        } else {
            $this->Session->setFlash('Please correct errors below.');
            unlink($destination.$this->Upload->result);
        }
    }
}

问题是图片不是来自add.ctp

这里是add.ctp代码

<label for="Image">Image:</label>
<input type="file" name="data[Image][filedata]" id="ImageFiledata" />

添加功能代码

    public function add() {
    $clint_ip=$this->request->clientIp();
    if ($this->request->is('post')) {

        $this->OesUser->create();

        pr($this->request->data);
        $this->request->data['OesUser']['user_otpkey']=String::uuid();
        $this->request->data['OesUser']['user_regdate']=date("Y-m-d H:i:s");
        $this->request->data['OesUser']['user_ip']=$clint_ip;
        $this->barcode($this->request->data['OesUser']['user_otpkey']);
        if ($this->OesUser->save($this->request->data)) {
            $this->Session->setFlash(__('The oes user has been saved'), 'flash_success');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The oes user could not be saved. Please, try again.'), 'flash_fail');
        }
    }
    $this->set('ip',$clint_ip);
}

这里,数据库字段名称:图像       控制器名称:OesUsers       型号名称:OesUser

为了完整的工作,我从这个链接中获得了帮助 http://labs.iamkoa.net/2007/10/23/image-upload-component-cakephp/

1 个答案:

答案 0 :(得分:0)

你的整个表单在add.ctp中是怎么样的?

听起来你没有添加

enctype="multipart/form-data"

到表格。这将导致表单不发布文件。

此外,建议使用Form helper来创建表单。 使用Form helper时,请指定要归档的表单类型

$this->Form->create('model',array('type'=>'file'));