0

我正在尝试使用Uploader Plugin 创建一个结构,User模型可以在其中上传模型的头像Avatar,我已经阅读了几次说明,但是当我尝试$this->Uploader->upload('Avatar.filename')没有验证错误但上传方法失败时。

这是我编写User模型的方式

<?php
class User extends AppModel {
    public $name = 'User';
    public $hasOne = array(
        'Profile' => array(
            'className' => 'Profile',
            'conditions' => '',
            'dependent' => true,
            'foreignKey' => 'user_id',
            'associatedKey' => 'user_id'
        ),
        'Avatar' => array (
            'className' => 'Avatar',
            'foreignKey' => 'user_id',
            'dependent' => true
        )
    );
    public $validate = array(...);
    // other stuff not relevant here...
?>

这是Avatar模型

<?php
class Avatar extends AppModel {
public $name = 'Avatar';
public $actsAs = array (
    'Uploader.Attachment' => array (
        'Avatar.filename' => array(
            'name'      => 'setNameAsImgId',    // Name of the function to use to format filenames
            'baseDir'   => '',                  // See UploaderComponent::$baseDir
            'uploadDir' => 'files/avatars/',    // See UploaderComponent::$uploadDir
            'dbColumn'  => 'filename',          // The database column name to save the path to
            'importFrom'    => '',              // Path or URL to import file
            'defaultPath'   => '',              // Default file path if no upload present
            'maxNameLength' => 500,             // Max file name length
            'overwrite' => true,                // Overwrite file with same name if it exists
            'stopSave'  => true,                // Stop the model save() if upload fails
            'allowEmpty'    => true,            // Allow an empty file upload to continue
            'transforms'    => array (
                array('method' => 'resize', 'width' => 128, 'height' => 128, 'dbColumn' => 'name')
            )       // What transformations to do on images: scale, resize, ete
        )
    ),
    'Uploader.FileValidation' => array (
        'Avatar.filename' => array (
            'maxWidth'  => array (
                'value' => 512,
                'error' => 'maxWidth error'
            ),
            'maxHeight' => array (
                'value' => 512,
                'error' => 'maxWidth error'
            ),
            'extension' => array (
                'value' =>  array('gif', 'jpg', 'png', 'jpeg'),
                'error' => 'extension error'
            ),
            'filesize'  => array (
                'value' => 5242880,
                'error' => 'filesize error'
            )
        )
    )
);

public $belongsTo = array(
    'User' => array(
        'className'     => 'User',
        'foreignKey'    => 'user_id',
        'conditions'    => '',
        'order'         => ''
    )
);

public function setNameAsImgId ($name, $field, $file) {
    /**
    * Format the filename a specific way before uploading and attaching.
    * 
    * @access public
    * @param string $name   - The current filename without extension
    * @param string $field  - The form field name
    * @param array $file    - The $_FILES data
    * @return string
    */
    // devo ricavare l'id dell'immagine appena creata per rinominare il file
    return $name;
}
}
?>

这是UsersControllerforedit方法

<?php
App::uses('CakeEmail','Network/Email');
CakePlugin::load('Uploader');
App::import('Vendor', 'Uploader.Uploader');

class UsersController extends AppController {
public $name = 'Users';

public function edit ($id) {
    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException ('Nessuna corrispondenza trovata per questo utente');
    }
    if (!$id) {
        $this->set('flash_element','error');
        $this->Session->setFlash ('Utente non valido');
    }
    $this->User->recursive = 1;
    $this->set('user', $this->User->read());

    if ($this->request->is('post')) {
        $this->User->id = $this->request->data['User']['id'];
        if (!$this->User->exists()) {
            $this->set('flash_element','warning');
            $this->Session->setFlash('Nessun utente trovato con questa corrispondenza');
    }
    if ($this->User->save($this->request->data)) {
        $this->request->data['Profile']['user_id'] = $this->User->id;

        $conditions = array(
            'conditions' => array(
                'Profile.id' => $this->request->data['Profile']['id']
            )
        );

        if ($this->User->Profile->save($this->request->data, $conditions)) {

            if (!empty($this->request->data['Avatar']['filename'])) {

                $this->request->data['Avatar']['user_id'] = $this->User->id;
                if ($this->User->Avatar->save($this->request->data)) {

                    $avatar = $this->User->Avatar->find('first', array(
                        'conditions' => array('Avatar.user_id' => $this->User->id)
                    ));
                    $ext = Uploader::ext($this->request->data['Avatar']['filename']);
                    $filename = $avatar['Avatar']['id'].'.'.$ext;


                if ($this->User->Avatar->save('Avatar.filename')) {
                    $this->set('flash_element','done');
                    $this->Session->setFlash('Avatar changed successfully');
                    debug('saved successfully');
                } else {
                    debug('not saved');
                    $this->set('flash_element','warning');
                    $this->Session->setFlash('Avatar not saved on the server');
                }

                } else {
                        $this->Session->write('flash_element','error');
                        $this->Session->setFlash('Avatar data not saved on the server');
                        $this->redirect(array('action'=>'index'));
                    }
                } else {
                    $this->Session->write('flash_element','done');
                    $this->Session->setFlash('Data successfully saved, avatar not changed');
                    $this->redirect(array('action'=>'index'));
                }
        } else {
                $this->set('flash_element','error');
                $this->Session->setFlash('Error on saving Profile data to the server');
            }
        } else {
            $this->Session->write('flash_element','error');
            $this->Session->setFlash('Error on saving User data to the server');
            $this->redirect(array('action'=>'index'));
        }
    }
}
}
?>

view文件中我有这个

<?php
echo $this->Form->create('User', array ('class' => 'form'));
echo $this->Form->input('User.id', array ('type'=>'hidden', 'value'=> $user['User']['id'],'label'=> false, 'id' => 'id'));
echo $this->Form->input('User.username', array ('label'=> false, 'value' => $user['User']['username'], 'id' => 'username', 'after' => '<div class="message">Message for username field'));
echo $this->Form->input('User.email', array ('label'=> false, 'value' => $user['User']['email'], 'id' => 'email', 'after' => '<div class="message">Message for email field</div>'));
echo $this->Form->input('UserOptions.id', array ('type'=>'hidden', 'value'=> $user['UserOptions']['id'],'label'=> false, 'id' => 'UserOptions.id'));
$attributes = array ('value' => $user['UserOptions']['avatar_type'], 'empty' => false);
$options = array('0' => 'This site', '1' => 'Gravatar');
echo $this->Form->select('UserOptions.avatar_type', $options, $attributes);
/* avatar code */
echo $this->Form->input('Avatar.id', array ('type'=>'hidden', 'value'=> $user['Avatar']['id'],'label'=> false, 'id' => 'Avatar.id'));
echo $this->Form->input('Avatar.filename', array('type' => 'file'));
/* end avatar code */
echo $this->Form->input('Profile.city', array ('label'=> false, 'value' => defaultValue ('City', $user['Profile']['city']), 'id' => 'city', 'after' => '<div class="message">Message for city field</div>'));
echo $this->Form->input('Profile.country', array ('label'=> false, 'value' => defaultValue('',$user['Profile']['country']), 'id' => 'country', 'after' => '<div class="message">Message for country field</div>'));
echo $this->Form->input('Profile.url', array ('label'=> false, 'value' => defaultValue('http://', $user['Profile']['url']), 'id' => 'url', 'after' => '<div class="message">Message for url field</div>'));
echo $this->Form->input('Profile.description', array ('label'=> false, 'value' => defaultValue('Description',$user['Profile']['description']), 'id' => 'description', 'after' => '<div class="message">Message for description field</div>'));
echo $this->Form->submit('Modifica', array('id'=>'edit'));
echo $this->Form->end();
?>

在控制器中,数据的每一部分都是saved直到我到达$this->Uploader->upload('Avatar.filename', array('overwrite' => true, 'name' => $filename))我得到一般错误的地方。

这个插件似乎是最好的方法,无需编写大量代码,但我不知道如何使用它。我不确定代码有什么问题,您能帮我解决问题吗?

4

1 回答 1

0

我发现了问题,我忘记了两件事:

view我忘记的页面中'type' => 'file'

<?php
echo $this->Form->create('User', array ('class' => 'form', 'type' => 'file'));
?>

我习惯于使用 1.3 版本,因此app/Config/bootstrap.php缺少配置:

<?php
CakePlugin::load('Uploader');
?>

现在它起作用了!

于 2012-06-27T22:14:42.167 回答