I'm trying to setup jQuery-File-Upload UI with oneupuploaderBundle on a symfony2 Website.
After a lot of tears, the upload process works as I want,but I can't make the Json response work avec the upload.
I use the PostUploadEvent of the oneupuploaderBundle, And tied a lot of solution to send a corecte jSon response to jQuery-File-Upload UI, but i still have an error message when the file has been uploaded.
In the doc, the ask to send a resonse like this:
{"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"
}
]}
Here is mine :
{"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"
}
] }
The URls are OK. I tried to return the response with
return new JsonResponse($jsonResponse);
with the Normal response object and json headers, I tried to create an entity and serialize it :
$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) );
And also to use the $event->getRequest(); of the object. But nothing works.
Is their someone who can help me please ? Thank you in advance.
Here is the complete file
<?php
namespace Reyner\Ishowpro\LibraryBundle\Upload;
use Oneup\UploaderBundle\Event\PostUploadEvent;
use Oneup\UploaderBundle\Event\PreUploadEvent;
use Reyner\Ishowpro\LibraryBundle\Tools\Tools;
use Reyner\Ishowpro\LibraryBundle\Entity\Folder;
use Reyner\Ishowpro\LibraryBundle\Entity\File;
use Reyner\Ishowpro\LibraryBundle\Entity\JqUploaderFile;
use Symfony\Component\HttpFoundation\File\File as sfFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Gaufrette\File as GaufretteFile;
class UploadListener
{
private $doctrine;
private $logger;
private $router;
public function __construct($doctrine, $logger, \Symfony\Bundle\FrameworkBundle\Routing\Router $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 Gaufrette\File or Symfony\Component\HttpFoundation\File\File.
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;
*/
}
}
Thanks to devsheeep, here is the solution. Really simple when you know it :
$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;
And we are in an Event context, return values have no effects. Instead we are working with references. So just omit the return statement.
5 to create it, I love. Thanks again to desheep and the 1up.io team, they are great professionals of the Symfony Framework.