我在这个Rails教程中使用了带有JQuery Upload的Rails Carrier Wave ,但是在按下Upload 按钮时出现错误:
Error: SyntaxError: JSON.parse
任何建议/建议都非常有用。
为什么不尝试Uploadify?
添加gem 'carrier_wave'到您的Gemfile。
gem 'carrier_wave'
将此代码保存到/lib/flash_session_cookie_middleware.rb:
/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此代码并将其添加到文件末尾:
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
/public/javascripts
uploadify.swf
cancel.png
/app/assets/images/
/public/images
uploadify.css
/app/assets/stylesheets/
/public/stylesheets
编辑您的application.js并在下面插入:
//= require swfobject //= require jquery.uploadify
在您的上传页面中,添加以下内容:
<input id="uploadify" name="uploadify" type="file"/>
将此代码添加到您的上传脚本中:
$(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进行了测试。