File Uploading using plupload plugin of jquery. « Intelligrape Groovy & Grails Blogs

File Uploading using plupload plugin of jquery.

Posted by

In my grails project i was having the requirement of having multiple file uploading, but in current implementation there was the problem of button being not loaded in Internet Explorer.For that i found plupload very cool to implement this. It has very cool feature of drag and drop and support for almost all browser. Actually what it does is based on the browser, get the Runtime of the browser.For Documentation, js and css refer link

In gsp we need to include the js of pluplaod api as shown below:

<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'plupload.queue.css')}" type="text/css" media="screen">
<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'jquery.ui.plupload.css')}" type="text/css" media="screen">
<g:set var="fileExtension" value="${new FileExtension()}"></g:set>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<p:javascript src='jquery-1.3.2'/>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "gears_init.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "browserplus-min.js")}"></script>
<!-- Load source versions of the plupload script files -->
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.gears.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.silverlight.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.flash.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.browserplus.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.html5.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "jquery.plupload.queue.js")}"></script>
<script type="text/javascript">
    var button = '${buttonId}';
</script>

Now we need to write script to load and bind the plupload plugin shown below:

	<script type="text/javascript">
    var runtimesList;
    if (navigator.userAgent.indexOf("Firefox")!=-1){
        runtimesList='silverlight,browserplus,html4,gears,flash,html5';
    }else{
        runtimesList='html5,silverlight,browserplus,html4,gears,flash';
    }
    $(function() {
        var uploader = new plupload.Uploader({
            runtimes : runtimesList,
            browse_button : 'pickfiles',
            url : url,
            flash_swf_url : '${resource(dir: "js/plupload", file: "plupload.flash.swf")}',
            silverlight_xap_url : '${resource(dir: "js/plupload", file: "plupload.silverlight.xap")}',
            filters : [
                {title : "Image files", extensions : "gif,png"},
                {title : "Zip files", extensions : "zip"}
            ]
        });

        uploader.bind('Init', function(up, params) {
        });

        uploader.bind('FilesAdded', function(up, files) {
            $.each(files, function(i, file) {
                $('#filelist').append('<div id="' + file.id + '"><span class="mcentd9d" style="font-size:12px; color:green;">File: ' + file.name + ' uploaded successfully!(' + plupload.formatSize(file.size) + ')<b></b><\/span>' + '</div>');
            });
        });

        uploader.bind('UploadFile', function(up, file) {

        });

        uploader.bind('UploadProgress', function(up, file) {
            $('#' + file.id + " b").html(file.percent + "%");
        });

        uploader.bind('QueueChanged', function(up) {
            $('#uploadfiles').click();
        });

        uploader.bind('FileUploaded', function(up) {

        });
        uploader.bind('Error', function(up) {
            alert('Error in uploading file');
        });

        $('#uploadfiles').click(function(e) {
            uploader.start();
            e.preventDefault();
        });
        uploader.init();
    });

</script>
	<div class="attachment">
               <div id="filelist"></div>
                      <a href="#" class="plupload_button plupload_add" id="pickfiles" style="position: relative; z-index: 0; ">Select File</a>
                      <input type='hidden' id="uploadfiles"/>
          </div>

Now we need to handle the saving part of the file,for each file uploaded in Queue there is separate call to
the action.It saves the file to the filePath specified.

def saveAttachment={
      def files = request.getFileMap()
      def file=files.get("file")
      String fileName = file.getOriginalFilename()
      byte[] data=file.getBytes()
      File dir=new File(filePath)//some path...
      if(!dir.exists()){
         dir.mkdirs()
      }
      File actualFile=new File(filePath, fileName)
      actualFile.withOutputStream {out ->
             out.write data
      }
}

Disclaimer: As in some cases you might want to can the upload of all the files as there is a different call to action of you can save there files in session, but session for this plupload is different from current user session so you will have to make your own session handling for that!!!

Note:The total length of files upload and and total uploaded differs in case IE and Firefox. The comments and any suggestions are welcomed.

Hope it help you guys! Cheer! :)

Anuj Aneja

http://www.Intelligrape.com

This entry was posted on February 14th, 2011 at 6:20 pm and is filed under Grails, Javascript/Ajax/JQuery . You can follow any responses to this entry through the RSS 2.0 feed. Responses are currently closed, but you can trackback from your own site.

7 Responses to “File Uploading using plupload plugin of jquery.”

  1. [...] This post was mentioned on Twitter by Robbie James, baselogic. baselogic said: File Uploading using plupload plugin of jquery.: In my grails project i was having the requireme… http://bit.ly/fkaUiI #Groovy #Grails [...]

  2. It is the best time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or suggestions. Maybe you can write next articles referring to this article. I desire to read more things about it!

  3. Thanks for another great article. Where else could anyone get that kind of info in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such information.

  4. I’m really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one these days..

  5. Just appropriate to comment once more convey which i genuinely love your weblog textile plus the point out domination which you effect keenly. It’s inordinately snappy to envisage a blogger assume good you.. alimony concrete up…

  6. free online says:

    I will right away grab your rss feed as I can not find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know in order that I could subscribe. Thanks.

  7. I have recently started a website, the info you offer on this web site has helped me greatly. Thank you for all of your time & work.