如何使用Cakephp 3.0上传文件?

时间:2015-05-13 08:47:47

标签: cakephp cakephp-3.0

我正在尝试在cakephp上创建一个文件上传,我还没有能够为cakephp 3.0找到任何体面的教程,详细介绍,我不知道如何安装插件。

我在添加部分

中有这个
/**
 * Index method
 *
 * @return void
 */
public function index()
{
    $this->paginate = [
        'contain' => ['Courses']
    ];
    $this->set('contents', $this->paginate($this->Contents));
    $this->set('_serialize', ['contents']);
}

/**
 * View method
 *
 * @param string|null $id Content id.
 * @return void
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function view($id = null)
{
    $content = $this->Contents->get($id, [
        'contain' => ['Courses']
    ]);
    $this->set('content', $content);
    $this->set('_serialize', ['content']);
}

/**
 * Add method
 *
 * @return void Redirects on successful add, renders view otherwise.
 */
public function add()
{
    $content = $this->Contents->newEntity();
    if ($this->request->is('post')) {
        $content = $this->Contents->patchEntity($content, $this->request->data);
        if ($this->Contents->save($content)) {
            $this->Flash->success('The content has been saved.');
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error('The content could not be saved. Please, try again.');
        }
    }
    $courses = $this->Contents->Courses->find('list', ['limit' => 200]);
    $this->set(compact('content', 'courses'));
    $this->set('_serialize', ['content']);
}

/**
 * Edit method
 *
 * @param string|null $id Content id.
 * @return void Redirects on successful edit, renders view otherwise.
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function edit($id = null)
{
    $content = $this->Contents->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $content = $this->Contents->patchEntity($content, $this->request->data);
        if ($this->Contents->save($content)) {
            $this->Flash->success('The content has been saved.');
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error('The content could not be saved. Please, try again.');
        }
    }
    $courses = $this->Contents->Courses->find('list', ['limit' => 200]);
    $this->set(compact('content', 'courses'));
    $this->set('_serialize', ['content']);
}

/**
 * Delete method
 *
 * @param string|null $id Content id.
 * @return void Redirects to index.
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function delete($id = null)
{
    $this->request->allowMethod(['post', 'delete']);
    $content = $this->Contents->get($id);
    if ($this->Contents->delete($content)) {
        $this->Flash->success('The content has been deleted.');
    } else {
        $this->Flash->error('The content could not be deleted. Please, try again.');
    }
    return $this->redirect(['action' => 'index']);
}

我还没有在控制器中添加任何东西

Type

但在此之后不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

首先,您需要决定何时处理上传。我设法使用beforeMarshal方法和afterSave方法创建一个肮脏(但工作)的方法(我将在最后解释为什么这两个)。

如果您创建文件输入,请执行以下操作:

<?= $this->Form->file('submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>

或hasMany关联:

<?= $this->Form->file('images.'.$i.'.submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>

并定义正确的关联:

$this->hasMany('Images', [
            'foreignKey' => 'model_id'
        ]);

您可以在修补并保存实体之前处理这些文件:

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options) {
        $images = array();
        $dir = md5(time().$data['name']);
        for ($i = 0; $i < count($data['images']); $i++) {
            $image = $data['images'][$i]['submittedfile'];
            if (!empty($image['name'])) {
                if(!isset($data['id'])) {
                    $data['temp_dir'] = $dir;
                }
                else {
                    $dir = $data['id'];
                }
                if ($this->Images->uploadFile(array('img', 'model', $dir), $image) === true) {
                    $images[] = array('name' => pathinfo($image['name'], PATHINFO_FILENAME), 'ext' => pathinfo($image['name'], PATHINFO_EXTENSION));
                }
            }
        }
        $data['images'] = $images;
    }

这当然是一个例子。我已经决定检查,如果在实体上设置了ID属性(比如编辑),因为如果它没有(比如创建),你必须以某种方式识别正确的路径

您已获得文件上传功能:

public function uploadDir($path = array()) {
        return $this->wwwRoot . implode(DS, $path);
    }

    public function uploadFile($path = array(), $filetoupload = null) {
        if (!$filetoupload) {
            return false;
        }
        $dir = new Folder($this->uploadDir($path), true, 755);
        $tmp_file = new File($filetoupload['tmp_name']);
        if (!$tmp_file->exists()) {
            return false;
        }
        $file = new File($dir->path . DS . $filetoupload['name']);
        if (!$tmp_file->copy($dir->pwd() . DS . $filetoupload['name'])) {
            return false;
        }
        $file->close();
        $tmp_file->delete();
        return true;
    }

如果您在没有包含主要实体ID的子目录时添加了图像,则必须在获得ID后立即重命名该目录:

public function afterSave(Event $event, Entity $entity, \ArrayObject $options) {
        if(!empty($entity->temp_dir)) {
            $this->Images->renameFolder(array('img', 'model', $entity->temp_dir),$entity->id);
        }
    }

主叫:

public function renameFolder($path = array(), $newName) {
        $oldPath = $this->wwwRoot . implode(DS, $path);
        $nameToChange = array_pop($path);
        array_push($path, $newName);
        $newPath = $this->wwwRoot . implode(DS, $path);
        return rename($oldPath, $newPath);
    }
  1. 使用beforeMarshal,您可以在整个实体准备好保存(带关联)之前将文件数据注入实体结构。
  2. 使用afterSave,您可以识别主要对象ID并调用之前已上传的对象集。
  3. 请记住设置将文件保存到目录的递归权限,以及创建和重命名目录的权限。