【问题标题】:ZF2 Handling File Uploads. How to access the uploaded files?ZF2 处理文件上传。如何访问上传的文件?
【发布时间】:2013-04-17 16:31:19
【问题描述】:

我在手册中看到了很多关于创建表单以上传文件的问题和信息。我已经能够设置一个表单来处理文件上传。下载文件后是否有任何基于 Zend 的代码来处理文件。

每个教程或手册参考似乎都有类似的内容:

if ($form->isValid()) {
    //
    // ...Save the form...
    //
}

我可以使用像 move_uploaded_file 这样的原生 php 函数来管理上传。我是否遗漏了什么,或者 Zend 只是回退到使用临时文件名作为其他代码中的数据?

【问题讨论】:

    标签: php file-upload zend-framework2


    【解决方案1】:

    说明书上有

    http://framework.zend.com/manual/2.1/en/modules/zend.form.file-upload.html

    // File: MyController.php
    
    public function uploadFormAction()
    {
        $form = new UploadForm('upload-form');
    
        if ($this->getRequest()->isPost()) {
            // Make certain to merge the files info!
            $post = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
    
            $form->setData($post);
            if ($form->isValid()) {
                $data = $form->getData();
                // Form is valid, save the form!
                return $this->redirect()->toRoute('upload-form/success');
            }
        }
    
        return array('form' => $form);
    }
    

    文件上传成功后,$form->getData() 会返回:

    array(1) {
        ["image-file"] => array(5) {
            ["name"]     => string(11) "myimage.png"
            ["type"]     => string(9)  "image/png"
            ["tmp_name"] => string(22) "/private/tmp/phpgRXd58"
            ["error"]    => int(0)
            ["size"]     => int(14908679)
        }
    }
    

    使用从$form->getData() 获得的数组来处理上传的文件。

    您还可以使用名为的过滤器设置目标并重命名。

    下面的链接对此有很好的解释:

    http://framework.zend.com/manual/2.1/en/modules/zend.filter.file.rename-upload.html#zend-filter-file-rename-upload

    希望这会有所帮助。

    【讨论】:

    • RenameUpload 的链接正是我想要的。我看到了所有带有// Form is valid, save the form! 的手册页,我读到的都是// Here should be the code you were looking for!。我编辑了答案以突出显示过滤和链接。
    • 感谢@Chris,纠正我的帖子,它也帮助其他正在寻找同样问题的人
    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2010-12-30
    • 2013-03-24
    • 1970-01-01
    • 2011-08-17
    • 2016-09-08
    • 2010-09-14
    • 2017-02-18
    相关资源
    最近更新 更多