接收时出现Zend \ File \ Transfer \ Adapter \ Http:错误"找不到文件"使用jQuery文件上传

时间:2014-05-19 03:29:53

标签: php jquery file-upload zend-framework2 jquery-file-upload

以下是关于此问题的两个问题

Zf2 file upload by jQuery File Upload - file was not found

Can't get blueimp / jQuery-File-Upload and ZF2 running

没有激光。我在ZF2上用代码示例创建问题。 github.com/zendframework/zf2/issues/6291

还有其他开发人员在我的电子邮件中提出问题的请求,如何使用ZF2实现jQuery文件上传。

github.com/blueimp/jQuery-File-Upload

所以,很多人都有真正的问题,没有任何手册,没有答案。 请在发送给我阅读文档之前注意,我花了很多时间解决问题并且已经阅读了所有文档,而且我不仅有这个问题。

请使用代码示例编写手册,例如如何实现它。或者只是回答,为什么我们有这个错误以及如何解决它?

我从ZF2问题中复制了我的例子。

我尝试使用jQuery-File-Upload 只需复制标准tpl,包括css和scrypts,它的工作,将文件发送到我的控制器。 但控制器不起作用。

这是我的代码

public function processjqueryAction()
    {
        $request   = $this->getRequest();
        $response  = $this->getResponse();
        $jsonModel = new \Zend\View\Model\JsonModel();

        if ($request->isPost()) {

            try {
                $datas          = [];
                $datas['files'] = [];
                $uploadPath     = $this->getFileUploadLocation();
                $uploadFiles    = $this->params()->fromFiles('files');

//                throw new \Exception(json_encode("FILES " . serialize($_FILES)));

                // Сохранение выгруженного файла
                $adapter = new \Zend\File\Transfer\Adapter\Http();
                $adapter->setDestination($uploadPath);
                $adapter->setValidators(array(
                    new \Zend\Validator\File\Extension(array(
                        'extension' => array('jpg', 'jpeg', 'png', 'rtf')
                            )
                    ),
//                    new \Zend\Validator\File\Upload()
                ));

                if (!$adapter->isValid()) {
                    throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                }

                $files = $adapter->getFileInfo();
//                throw new \Exception(json_encode($files));

                foreach ($files as $file => $info) {
//                    throw new \Exception(json_encode($info));

                    $name = $adapter->getFileName($file);

                    // file uploaded & is valid
                    if (!$adapter->isUploaded($file)) {
                        throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages()));
                        continue;
                    }

                    if (!$adapter->isValid($file)) {
                        throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                        continue;
                    }

                    // receive the files into the user directory
                    $check = $adapter->receive($file); // this has to be on top

                    if (!$check) {
                        throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages())));
                    }

                    /**
                     * "name": "picture1.jpg",
                      "size": 902604,
                      "url": "http:\/\/example.org\/files\/picture1.jpg",
                      "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
                      "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
                      "deleteType": "DELETE"
                     */
                    $fileclass             = new stdClass();
                    // we stripped out the image thumbnail for our purpose, primarily for security reasons
                    // you could add it back in here.
                    $fileclass->name       = $name;
                    $fileclass->size       = $adapter->getFileSize($name);
                    $fileclass->type       = $adapter->getMimeType($name);
                    $fileclass->deleteUrl  = '/uploads/delete';
                    $fileclass->deleteType = 'DELETE';
                    //$fileclass->error = 'null';
                    $fileclass->url        = '/';

                    $datas['files'][] = $fileclass;
                }

                $response->getHeaders()->addHeaders(array(
                    'Pragma'        => 'no-cache',
                    'Cache-Control' => 'private, no-cache',
                    "Content-Type"  => 'application/json'
                ));

//                return $response->setContent(json_encode(array('files' => $files)));
                return $response->setContent(json_encode($datas));
            } catch (\Exception $e) {

                return $response->setContent(json_encode($e->getMessage()));
            }
        }

        return $jsonModel;

}

很抱歉调试代码,但有了它,你可以看到,我努力让它工作,超过3个小时。

错误是 “未找到”文件'CIMG0042.JPG'

当我打电话给$ adapter-> isValid() 或者用文件名称调用它时,同样的错误。 上传文件的路径是正确且可写的。 $ _FILES数组存在且有效。

这是$ _FILES json

FILES a:1:{s:5:\"files\";a:5:{s:4:\"name\";a:1:{i:0;s:28:\"52876065d17dce0a7472e5d6.jpg\";}s:4:\"type\";a:1:{i:0;s:10:\"image\/jpeg\";}s:8:\"tmp_name\";a:1:{i:0;s:14:\"\/tmp\/phpmfT2mB\";}s:5:\"error\";a:1:{i:0;i:0;}s:4:\"size\";a:1:{i:0;i:82640;}}}

$ files = $ adapter-> getFileInfo();

的结果
"{"files_0_":{"name":"52876065d17dce0a7472e5d6.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpF6VoO9","error":0,"size":"82640","options":{"ignoreNoFile":false,"useByteString":true,"magicFile":null,"detectInfos":true},"validated":false,"received":false,"filtered":false,"validators":["Zend\\Validator\\File\\Upload","Zend\\Validator\\File\\Extension"],"destination":"\/home\/seyfer\/www\/zend2-tutorial.me\/module\/Users\/config\/..\/..\/..\/data\/uploads"}}"

isUploaded传递,但isValid没有。

我做错了什么?

文档说这个

  

Zend_File_Transfer已被弃用,转而使用标准的ZF2 Zend \ Form和Zend \ InputFilter功能。

也许这意味着,Form需要以任何方式用于文件上传?

UPD 25.05.14

现在我添加表格

class UploadJqueryForm extends BaseForm
{

    public function __construct()
    {
        parent::__construct(__CLASS__);
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype', 'multipart/form-data');

        $this->init();
    }

    public function init()
    {
        $fileupload = new Element\File('files');
        $fileupload->setLabel("files");
        $fileupload->setAttribute('multiple', 'multiple');
        $this->add($fileupload);

        $button = new Element\Button('start');
        $button->setAttribute("type", 'submit');
        $button->setValue("Start upload")->setLabel("Start upload");
        $this->add($button);

        $button = new Element\Button('cancel');
        $button->setAttribute("type", 'reset');
        $button->setValue("Cancel upload")->setLabel("Cancel upload");
        $this->add($button);

        $button = new Element\Button('delete');
        $button->setAttribute("type", 'button');
        $button->setValue("Delete")->setLabel("Delete");
        $this->add($button);

        $checkbox = new Element\Checkbox('toggle');
        $checkbox->setValue("Toggle")->setLabel("Toggle");
        $checkbox->setAttribute("required", "");
        $this->add($checkbox);
    }

}

使用它

public function processjqueryAction()
    {
        $form      = new \Users\Form\UploadJqueryForm();
        $request   = $this->getRequest();
        $response  = $this->getResponse();
        $jsonModel = new \Zend\View\Model\JsonModel();

        try {

            if ($request->isPost()) {

                $data = array_merge_recursive(
                        $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
                );

//                throw new \Exception(json_encode("data " . serialize($data)));

                $form->setData($data);
                if ($form->isValid()) {
                    $datas          = [];
                    $datas['files'] = [];
                    $uploadPath     = $this->getFileUploadLocation();
//                $uploadFiles    = $this->params()->fromFiles('files');
//                throw new \Exception(json_encode("FILES " . serialize($_FILES)));
                    // Сохранение выгруженного файла
                    $adapter        = new \Zend\File\Transfer\Adapter\Http();
                    $adapter->setDestination($uploadPath);
                    $adapter->setValidators(array(
                        new \Zend\Validator\File\Extension(array(
                            'extension' => array('jpg', 'jpeg', 'png', 'rtf')
                                )
                        ),
                    ));

                    if (!$adapter->isValid()) {
                        throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                    }

                    $files = $adapter->getFileInfo();
//                throw new \Exception(json_encode($files));

                    foreach ($files as $file => $info) {
//                    throw new \Exception(json_encode($info));

                        $name = $adapter->getFileName($file);

                        // file uploaded & is valid
                        if (!$adapter->isUploaded($file)) {
                            throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages()));
                            continue;
                        }

                        if (!$adapter->isValid($file)) {
                            throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                            continue;
                        }

                        // receive the files into the user directory
                        $check = $adapter->receive($file); // this has to be on top

                        if (!$check) {
                            throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages())));
                        }

                        /**
                         * "name": "picture1.jpg",
                          "size": 902604,
                          "url": "http:\/\/example.org\/files\/picture1.jpg",
                          "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
                          "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
                          "deleteType": "DELETE"
                         */
                        $fileclass             = new stdClass();
                        // we stripped out the image thumbnail for our purpose, primarily for security reasons
                        // you could add it back in here.
                        $fileclass->name       = $name;
                        $fileclass->size       = $adapter->getFileSize($name);
                        $fileclass->type       = $adapter->getMimeType($name);
                        $fileclass->deleteUrl  = '/uploads/delete';
                        $fileclass->deleteType = 'DELETE';
                        //$fileclass->error = 'null';
                        $fileclass->url        = '/';

                        $datas['files'][] = $fileclass;
                    }

                    $response->getHeaders()->addHeaders(array(
                        'Pragma'        => 'no-cache',
                        'Cache-Control' => 'private, no-cache',
                        "Content-Type"  => 'application/json'
                    ));

                    return $response->setContent(json_encode($datas));
                } else {
                    throw new \Exception(json_encode("!isValid form" . serialize($form->getMessages())));
                }
            }
        } catch (\Exception $e) {

            return $response->setContent(json_encode($e->getMessage()));
        }

        return $jsonModel;

仍然会出错 找不到文件'24866-fu-blyad-otvratitelno.jpg'

我也尝试使用InputFilter

class UploadJqueryFilter extends InputFilter implements
InputFilterAwareInterface
{

    public function __construct()
    {
        $this->getInputFilter();
    }

    public function getInputFilter()
    {
        $toggle = new Input('toggle');
        $toggle->setRequired(FALSE);
        $this->add($toggle);

        $files = new \Zend\InputFilter\FileInput('files');
        $files->setRequired(TRUE);
        $files->getValidatorChain()->attach(new Validator\File\UploadFile);
        $files->getFilterChain()->attach(new \Zend\Filter\File\RenameUpload(array(
            'target'    => __DIR__ . '/../../../../../../tmpuploads/tmp',
            'randomize' => true,
        )));
        $this->add($files);

        return $this;
    }

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        return false;
    }

}

并有同样的错误。

1 个答案:

答案 0 :(得分:4)

我也有这个问题。在发现问题之前浪费了几个小时。结果是因为输入标签的名称属性不能设置为“文件”

所以这是一个no:

INFO

将名称属性更改为文件以外的任何字符串,例如文件,可以解决此问题。

<input id="files" type="file" name="files" data-url="/upload-action" />

我从$ _FILES看到您已将名称设置为文件。尝试改变它。 确保更新控制器中的参考。