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.
Why not try Uploadify?
Add gem 'carrier_wave'
to you Gemfile.
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
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]
)
Download Uploadify and unzip it.
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.uploadify.swf
and cancel.png
to /app/assets/images/
or
/public/images
.uploadify.css
to /app/assets/stylesheets/
or
/public/stylesheets
.Edit your application.js and insert below:
//= require swfobject
//= require jquery.uploadify
In you upload page, add this:
<input id="uploadify" name="uploadify" type="file"/>
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) {
}
});
});
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.