Recent posts


Recent comments


Archives

Archives for January 2009


Getting up and running with SWFUpload on Merb and jQuery

January 04, 2009 6 comments

SWFUpload is a great javascript kit for adding nice, multiple file uploads to your application. Today were going to go through the steps to get SWFUpload working with Merb 1.x. All this code is valid for SWFUpload v 2.2.0, which you can download here.


Generate your new merb app

        merb-gen app picture_place


Create the picture resource
We will need a picture model to store our pictures, so lets create that now.

        merb-gen resource picture


Install dm-paperclip
Paperclip is a great gem for handling picture uploads. Open up /config/dependencies.rb and add the following

        dependency "dm-paperclip"


Setup the picture model
Add the following to /app/models/picture.rb

        include Paperclip::Resource
        has_attached_file :image,
          :default_url => "/uploads/pictures/:attachment/missing_:style.png",
          :url => "/uploads/pictures/:id/:style/:basename.:extension",
          :path => ":merb_root/public/uploads/pictures/:id/:style/:basename.:extension",
          :styles => {:small => "55x55#", :medium => "100x100#", :large => "600x600>" }
The has_attached_file method is where you setup paperclip options. :default_url is the image to show if paperclip can't find the requested image. :url is the place where your images get stored. :path is the path the image is served from. :styles creates thumbnails out of your picture, you can define custom sizes here. The has_attached_file method will also add all the columns to the database that are needed such as content-type, filename etc.



Setup the router
Were going to want to use an action in the picture controller called 'swf_upload' to handle uploads coming from SWFUpload, so lets set that up in the router.

        with(:controller => "pictures") do
          match('/pictures/swf_upload').to(:action => "swf_upload").fixatable
        end
Notice the .fixatable on the end of the match method, this is important for passing session info through flash and back again.



Setup the controller
Open up your pictures controller and add the following.

        def swf_upload
          only_provides :html
          @picture = Picture.new
          @picture.image = params[:Filedata]
          ## If the picture belongs to a user, uncomment this line
          ## @picture.user_id = session.user.id
          if @picture.save
            return "success"
          else
            return ""
          end
        end
This is the basic method for handling your uploads. @picture.image = params[:Filedata] is what sets up all the info about the picture for the database.



Get the necessary files
We are going to need a few javascript files to SWFUpload, so were gonna grab those now. First create a new directory in public/ called swfupload. Then head over here, download all the files and put them in public/swfupload/


Now onto the view
Now for the fun stuff. Open up /app/views/pictures/new.html.haml and add the following

        %script{:type => "text/javascript", :src => "/swfupload/swfupload.js"}
        %script{:type => "text/javascript", :src => "/swfupload/swfupload.queue.js"}
        %script{:type => "text/javascript", :src => "/swfupload/fileprogress.js"}
        %script{:type => "text/javascript", :src => "/swfupload/handlers.js"}
        
        :javascript
          var swfu;
          $(document).ready(function(){
            var settings = {
              upload_url: "/pictures/swf_upload?_picture_place_session_id=#{cookies[:_picture_place_session_id]}",
              flash_url: "/swfupload/swfupload.swf",
              file_size_limit: "10485760", // 10 MB
              file_types: "*.jpg;*.png;*.gif",
              file_types_description: "JPG, GIF, or PNG Image Files",
              file_upload_limit : 100,
              file_queue_limit : 0,
              debug: false,
              custom_settings : {
                progressTarget : "images"
              },
              // Button settings
              button_width: "200",
              button_height: "32",
              button_placeholder_id: "browse",
              button_text: '<span class="theFont">Select files to upload</span>',
              button_text_style: ".theFont { font-size: 16; font-family: arial; }",
              // Handlers
              file_queued_handler : fileQueued,
              file_dialog_complete_handler: fileDialogComplete,
              upload_start_handler: uploadStart,
              upload_progress_handler: uploadProgress,
              upload_error_handler: uploadError,
              upload_success_handler: uploadSuccess,
              upload_complete_handler: uploadComplete
            };
            swfu = new SWFUpload(settings);
            // Add Event Handlers
            $('#browse').click(function() { swfu.selectFiles(); });
            $('#upload').click(function() { swfu.startUpload(); });
          });
        
        %h1 Upload some new pictures
        #upload-actions
          #browse Select Files
          %a.upload-button#upload{:href => '#', 'onclick' => 'return false'} Upload files
        #images
So whats going on here? The first two lines include the javascript files we need. Most of the settings are self explanatory, but note the upload_url line, were passing the users session key through so that we know which user uploaded the picture in the swf_upload action. This will give us a basic working upload form, go ahead and fire up merb and give it a shot.



Give it a test run
We now have working uploads, fire up your browser and head to http://localhost:4000/pictures/new and try uploading some pictures. I have a sample app made up on github you can check also look at.