草庐IT

php - Zend\File\Transfer\Adapter\Http on receive : error "File was not found" with jQuery File Upload

coder 2024-05-03 原文

这里已经有两个关于这个问题的问题了

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 即可,将文件发送到我的 Controller 。 但是 Controller 不起作用。

这是我的代码

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 has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.

也许这意味着,无论如何都需要使用 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;
    }

}

并且有同样的错误。

最佳答案

我也遇到过这个问题。浪费了几个小时才发现问题。原来是因为input标签的name属性不能设置为'files'

所以这是一个不:

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

将 name 属性更改为 files 以外的任何字符串,例如 file 将解决此问题。

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

我从 $_FILES 中看到您已将名称设置为文件。尝试改变它。 确保你也更新了你在 Controller 中所做的引用。

关于php - Zend\File\Transfer\Adapter\Http on receive : error "File was not found" with jQuery File Upload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729308/

有关php - Zend\File\Transfer\Adapter\Http on receive : error "File was not found" with jQuery File Upload的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - Ruby on Rails : . 常量化 : wrong constant name error? - 2

    我正在使用这个:4.times{|i|assert_not_equal("content#{i+2}".constantize,object.first_content)}我之前声明过局部变量content1content2content3content4content5我得到的错误NameError:wrongconstantnamecontent2这个错误是什么意思?我很确定我想要content2=\ 最佳答案 你必须用一个大字母来调用ruby​​常量:Content2而不是content2。Aconstantnamestart

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  8. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  9. ruby CSV : How can I read a tab-delimited file? - 2

    CSV.open(name,"r").eachdo|row|putsrowend我得到以下错误:CSV::MalformedCSVErrorUnquotedfieldsdonotallow\ror\n文件名是一个.txt制表符分隔文件。我是专门做的。我有一个.csv文件,我转到excel,并将文件保存为.txt制表符分隔的文件。所以它是制表符分隔的。CSV.open不应该能够读取制表符分隔的文件吗? 最佳答案 尝试像这样指定字段分隔符:CSV.open("name","r",{:col_sep=>"\t"}).eachdo|row|

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐