Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Carrier Wave with JQuery Uploader

I am using Rails Carrier Wave with JQuery Upload like on this rails tutorial, but I am having an error when I hit the upload button :

Error: SyntaxError: JSON.parse

Any advise/suggestions are much appriciated.

like image 457
King Pangilinan Avatar asked Dec 02 '11 22:12

King Pangilinan


1 Answers

Why not try Uploadify?

Step 1

Add gem 'carrier_wave' to you Gemfile.

Step 2

Save this code to /lib/flash_session_cookie_middleware.rb:

require 'rack/utils'

class FlashSessionCookieMiddleware
  def initialize app, session_key = '_session_id'
    @app = app
    @session_key = session_key
  end

  def call env
    if env['HTTP_USER_AGENT'] =~ /^(Adobe|Shockwave) Flash/
      request = Rack::Request.new env
      env['HTTP_COOKIE'] = [@session_key, request.params[@session_key]].join('=').freeze unless request.params[@session_key].nil?
      env['HTTP_ACCEPT'] = "#{request.params['_http_accept']}".freeze unless request.params['_http_accept'].nil?
    end

    @app.call env
  end
end

Step 3

Edit session_store.rb and add this code to the end of file:

Rails.application.config.middleware.insert_before(
  ActionDispatch::Session::CookieStore,
  FlashSessionCookieMiddleware,
  Rails.application.config.session_options[:key]
)

Step 4

Download Uploadify and unzip it.

Step 5

  1. Copy jquery.uploadify.v2.1.4.min.js and swfobject.js to /app/assets/javascripts if you use Rails 3.1 or later; to /public/javascripts if you use Rails 3.0 or an earlier version.
  2. Copy uploadify.swf and cancel.png to /app/assets/images/ or /public/images.
  3. Copy uploadify.css to /app/assets/stylesheets/ or /public/stylesheets.

Step 6

Edit your application.js and insert below:

//= require swfobject
//= require jquery.uploadify

Step 7

In you upload page, add this:

<input id="uploadify" name="uploadify" type="file"/>

Step 8

Add this code to you upload script:

$(document).ready(function() {
  <% key = Rails.application.config.session_options[:key] %>
  var uploadify_script_data = {};
  var csrf_param = $('meta[name=csrf-param]').attr('content');
  var csrf_token = $('meta[name=csrf-token]').attr('content');
  uploadify_script_data[csrf_param] = encodeURI(encodeURIComponent(csrf_token));
  uploadify_script_data['<%= key %>'] = '<%= cookies[key] %>';

  $('#uploadify').uploadify({
    uploader        : '/assets/uploadify.swf',
    script          : '/photos',
    cancelImg       : '/images/cancel.png',
    auto            : true,
    multi           : true,
    removeCompleted     : true,
    scriptData      : uploadify_script_data,
    onComplete      : function(event, ID, fileObj, doc, data) {
    }
  });
});

Step 9

Write your controller like this:

def create
  @photo = Photo.new image: params[:file_data]
  @photo.save
end

Note: This was tested with Uploadify 2.1.4.

like image 156
VvDPzZ Avatar answered Nov 07 '22 13:11

VvDPzZ