jquery file upload with symfony2

for use this plugin, install jquery-file-upload in web
install punk_ave bundle
and this is my example:

 
        /**
  * @Route("/import",name="prospection_admin_import")
  * @Template()
  */
 public function importAction(){
  $fileUploader = $this->get('punk_ave.file_uploader');  
  $request = $this->getRequest();
  $existingFiles=null;
  $editId = $request->query->get('editId');
  if (!$editId){
   $editId=$request->getSession()->get('editId');
  }
  if ($editId){
   $existingFiles = $fileUploader->getFiles(array('folder' => '/tmp/attachments/'. $editId));
   if ($request->getMethod() == 'POST') {
    $type=$request->request->get("importType");    
    $importHandler=$this->get('addepi.prospection.import.handler');
    $path=$this->get('kernel')->getRootDir()."/../web/uploads/tmp/attachments/".$editId."/originals/";
    
    foreach($existingFiles as $file){
     if (!$importHandler->importFile($path.$file,$type)){
      $this->get('session')->getFlashBag()->add('notice', 'Treat file error:'.$file);
      break;  
     }else
      $this->get('session')->getFlashBag()->add('notice', 'File treated :'.$file);
    }    
   }  
  }else{
   $editId = sprintf('%09d', mt_rand(0, 1999999999));
   $request->getSession()->set('editId',$editId);
  } 
  return array("editId"=>$editId);
 }

 /**
  * @Route("/upload",name="prospection_admin_upload" ,options={"expose"=true})
  * @Template()
  */
 public function uploadAction(){
  $editId = $this->getRequest()->get('editId');
  if (!preg_match('/^\d+$/', $editId) && $editId!='test')
  {
   throw new \Exception("Bad edit id");
  }  
  $this->get('punk_ave.file_uploader')->handleFileUpload(array('folder' => '/tmp/attachments/' . $editId));
 }
javascript is like this:
$(document).ready(function(){ 

   'use strict';

     // Initialize the jQuery File Upload widget:
     $('#fileupload').fileupload({
         // Uncomment the following to send cross-domain cookies:
         //xhrFields: {withCredentials: true},
         url: uploadUrl,
         maxChunkSize: 5000000,
     });

        // Load existing files:
        $('#fileupload').addClass('fileupload-processing');
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: uploadUrl,
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function (result) {
            $(this).removeClass('fileupload-processing');
        }).done(function (result) {
            $(this).fileupload('option', 'done')
                .call(this, null, {result: result});
        });
 
the string uploadurl is point to the upload action. And each time we just save the editId in the session and so we can have a list for session. or other wise, we can use it to individual upload process, such like for a announcement, profil etc.

评论

热门博文