oneupuploader with jQuery-File-Upload UI



我正试图在symfony2网站上使用oneupuploaderBundle设置jQuery File Upload UI。

在流了很多眼泪之后,上传过程按照我的意愿进行,但我无法使Json的响应在上传后正常工作。

我使用oneupuploaderBundle的PostUploadEvent,并绑定了很多解决方案来向jQuery File Upload UI发送一个corecte jSon响应,但当文件上传时,我仍然有一条错误消息。

在文档中,请求发送这样的回复:

{"files": [
  {
    "name": "picture1.jpg",
    "size": 902604,
    "url": "http://example.org/files/picture1.jpg",
    "thumbnail_url": "http://example.org/files/thumbnail/picture1.jpg",
    "delete_url": "http://example.org/files/picture1.jpg",
    "delete_type": "DELETE"
  }
]}

这是我的:

{"files": [ 
    { 
    "url": "/ishowpro-cms/web/app_dev.php/library/file/image/originals/51dbd9a13a065-screen-shot-mini.png",     
    "thumbnail_url": "/ishowpro-cms/web/app_dev.php/library/file/image/thumbnails/51dbd9a13a065-screen-shot-mini.png", 
    "name": "screen-shot-mini.png", 
    "type": "image/png", 
    "size": 1192, 
    "delete_url": "http://nourltodelete.com", 
    delete_type: "DELETE" 
    } 
] }

URL正常。我试图用返回响应

return new JsonResponse($jsonResponse); 

使用Normal响应对象和json头,我尝试创建一个实体并序列化它:

$responseObjectFile = new JqUploaderFile();
$responseObjectFile->setName();
$responseObjectFile->setSize();
$responseObjectFile->setUrl();
$responseObjectFile->setThumbnail_url();
$responseObjectFile->setDelete_url($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true));
$responseObjectFile->setDelete_type("DELETE");  

//create serializer to encode Entity
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($responseObjectFile, 'json');

//add entity in array and unserilize it....
$responseCode = array('files'=>array($jsonContent) );

还可以使用$event->getRequest();对象的。但什么都不管用。

他们有人能帮我吗?提前谢谢。


这是完整的文件

<?php
namespace ReynerIshowproLibraryBundleUpload;
use OneupUploaderBundleEventPostUploadEvent;
use OneupUploaderBundleEventPreUploadEvent;
use ReynerIshowproLibraryBundleToolsTools;
use ReynerIshowproLibraryBundleEntityFolder;
use ReynerIshowproLibraryBundleEntityFile;
use ReynerIshowproLibraryBundleEntityJqUploaderFile;
use SymfonyComponentHttpFoundationFileFile as sfFile;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentSerializerSerializer;
use SymfonyComponentSerializerEncoderXmlEncoder;
use SymfonyComponentSerializerEncoderJsonEncoder;
use SymfonyComponentSerializerNormalizerGetSetMethodNormalizer;
use GaufretteFile as GaufretteFile;

class UploadListener
{
    private $doctrine;
    private $logger;
    private $router;

    public function __construct($doctrine, $logger, SymfonyBundleFrameworkBundleRoutingRouter $router)
    {
        $this->doctrine = $doctrine;
        $this->logger = $logger;  
        $this->router = $router;
    }

    public function onPreUpload(PreUploadEvent $event)
    {           
        $file = $event->getFile();
    }
    public function onUpload(PostUploadEvent $event)
        {
            $this->logger->info('----------------------------------------------------');
            $this->logger->info('------------------    service begin ----------------------');

            $request = $event->getRequest();
            //$requestFile = $request->files->all();
            //$this->logger->info($requestFile["files"][0]->getClientOriginalName());
            $em = $this->doctrine->getManager();
            $tempfile = $event->getFile();

            $parameters = $request->request->all();

        /*  getFile: Get the uploaded file. Is either an instance of GaufretteFile or SymfonyComponentHttpFoundationFileFile.
            getRequest: Get the current request including custom variables.
            getResponse: Get the response object to add custom return data.
            getType: Get the name of the mapping of the current upload. Useful if you have multiple mappings and EventListeners.
            getConfig: Get the config of the mapping.
        */

                $parameters = $request->query->all();
                //stock ids to add "new" badges
                $newIds = array();
                    $folder  = $em->getRepository('LibraryBundle:Folder')->find($request->getSession()->get('currentFolder'));
                    $library = $em->getRepository('LibraryBundle:Library')->find($request->getSession()->get('libraryId'));
                //  $this->logger->info('folder: '.$folder->getId());
                    //persit in BDD
                    $file = new File();
                    $file->setLibrary($library);
                    $file->setFolder($folder);
                    $file->setSize($tempfile->getSize());
                    $filenamePart = explode("--", $tempfile->getName());
                    $pathinfo = pathinfo($tempfile->getName());
                    $file->setExtension(strtolower($pathinfo["extension"]));
                    $file->setName($pathinfo['filename']);


                    //check mime type and correct it if docx, xlsx or pptx
                    if(Tools::getMymeTypeFromExt($pathinfo["extension"])){
                        $file->setMimetype(Tools::getMymeTypeFromExt($pathinfo["extension"]));
                    }else{
                        $fi = new finfo(FILEINFO_MIME_TYPE);
                        $file->setMimetype($fi->buffer($tempfile->getContent()));
                    }
                    $file->setFilename($filenamePart[1]);
                    $em->persist($file);
                    $em->flush();


                    //create thumb
                    if($file->isImage()){
                        $this->logger->info('is an Image');
                        $imagepath = $file->getLocalFileDirectory().$tempfile->getName();
                        $this->logger->info('image path: '.$imagepath);
                        $file->encodeAndMoveFile($imagepath);
                        $this->logger->info('----------------------------------------------------');
                    }else{
                        $this->logger->info('is not an Image');
                        $this->logger->info($file->getLocalFileDirectory().$tempfile->getName());
                        $file->moveTempFile($file->getLocalFileDirectory().$tempfile->getName());
                    }

                    //add id to the New session array
                    if($request->getSession()->get("newfilesids")){
                        $newIds = unserialize($request->getSession()->get("newfilesids"));
                    }
                    $newIds[] = $file->getId();
                    $request->getSession()->set("newfilesids", serialize($newIds));
                    $this->logger->info('JqUploaderFile');
                    $this->logger->info('----------------------------------------------------');
                    /********************************************
                     * 
                     * BUILD RESPONSE
                     * 
                     ******************************************/
                    $this->logger->info('BUILD RESPONSE');
            /*//test1       
                    //create object needed to JqUploader response
                    $responseObjectFile = new JqUploaderFile();
                    $responseObjectFile->setName($file->getFileName());
                    $responseObjectFile->setSize($file->getSize());
                    $responseObjectFile->setUrl($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true));
                    $responseObjectFile->setThumbnail_url($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'thumbnails'), true));
                    $responseObjectFile->setDelete_url($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true));
                    $responseObjectFile->setDelete_type("DELETE");  
                    $this->logger->info('-------------------------------------------------------');
                    $this->logger->info('ENTITY READY');
            */  
            //test 2        
                    $response = $event->getResponse();
                    $response["file"][]['name'] = $file->getFileName();
                    $response["file"][]['size'] = $file->getSize();
                    $response["file"][]['url'] = $this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true);
                    $response["file"][]['thumbnail_url'] = $this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'thumbnails'), true);
                    $response["file"][]['delete_url'] = $this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true);
                    $response["file"][]['delete_type'] = "DELETE";

                    return $response;       


        //test 3
        /*
                $jsonResponse = '{"files": [ { "url": '.json_encode($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'originals'), true)).',  "thumbnail_url": '.json_encode($this->router->generate('show_image_link', array('slug'=>$file->getSlug(), 'extension'=>$file->getExtension(), 'size'=>'thumbnails'), true)).',  "name": '.json_encode($file->getFileName()).', "type": "'.$file->getMimeType().'", "size": '.$file->getSize().', "delete_url": "http://nourltodelete.com", "delete_type": "DELETE" } ] }';
                return $jsonResponse;
        */          

        }
}

感谢devsheeep,这里是解决方案。当你知道的时候真的很简单:

$response = $event->getResponse();
$files = array();
$files[0] = array(
        'name' => $file->getFileName(),
            'size' => $file->getSize(),
            'url'  => "Your URL",
            'thumbnail_url' => "Your thumb URL",
            'delete_url'   =>"Your delete URL",
            'delete_type' => 'DELETE'
            );
$response['files'] = $files;

并且我们处于事件上下文中,返回值没有任何影响。相反,我们正在使用参考资料。因此,只需省略return语句。

5创造它,我喜欢。再次感谢desheep和1up.io团队,他们是Symfony框架的优秀专业人士。

相关内容

  • 没有找到相关文章

最新更新