我在这个rails教程中使用Rails Carrier Wave和JQuery上传,但是当我点击上传按钮时出现错误:
Error: SyntaxError: JSON.parse
任何建议/建议都很受欢迎.
为什么不试试Uploadify?
添加gem 'carrier_wave'
到你的Gemfile.
将此代码保存到/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
编辑session_store.rb
并将此代码添加到文件末尾:
Rails.application.config.middleware.insert_before( ActionDispatch::Session::CookieStore, FlashSessionCookieMiddleware, Rails.application.config.session_options[:key] )
下载Uploadify并解压缩.
复制jquery.uploadify.v2.1.4.min.js
并swfobject.js
以
/app/assets/javascripts
如果您使用的Rails 3.1或更高版本; 到
/public/javascripts
如果使用的Rails 3.0或更早版本.
复制uploadify.swf
和cancel.png
到/app/assets/images/
或
/public/images
.
复制uploadify.css
到/app/assets/stylesheets/
或
/public/stylesheets
.
编辑您的application.js并在下面插入:
//= require swfobject //= require jquery.uploadify
在您上传页面中,添加以下内容:
将此代码添加到上传脚本:
$(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) { } }); });
像这样写你的控制器:
def create @photo = Photo.new image: params[:file_data] @photo.save end
注意:这是使用Uploadify 2.1.4测试的.