Skip to content

Instantly share code, notes, and snippets.

@jamesbebbington
Created September 24, 2010 11:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jamesbebbington/595213 to your computer and use it in GitHub Desktop.
# Adobe Flash fails to pass the correct mime-type when POSTing files.
# This piece of middleware is used to correctify the matter
#
# N.B. Requires `file` command so will probably only work on POSIX systems
#
# To use add this to an initializer:
# ActionController::Dispatcher.middleware.insert_after(ActionController::ParamsParser, IdentifyMimetypesMiddleware, /^(Adobe|Shockwave) Flash/)
require 'rack/utils'
class IdentifyMimetypesMiddleware
def initialize(app, user_agent)
@app = app
@user_agent = user_agent
end
def call(env)
if env['HTTP_USER_AGENT'] =~ @user_agent
if Rack::Request.new(env).params.present? && env["rack.request.query_hash"]
env["rack.request.query_hash"].each { |obj| identify(obj) }
end
end
@app.call(env)
end
def identify(obj)
if obj.respond_to?(:has_key?) && obj.has_key?(:tempfile) && obj[:tempfile].is_a?(Tempfile)
if obj[:type] == 'application/octet-stream'
matchdata = `#{AppConfig.webserver.path_to_file_bin}file --mime #{obj[:tempfile].path}`.match(/:\s+([-\w]+\/[-\.\w]+);?/)
if matchdata[1]
mime_type = matchdata[1]
obj[:type] = mime_type
obj[:head].gsub!('Content-Type: application/octet-stream', "Content-Type: #{mime_type}")
end
end
return
elsif !obj.is_a?(String) && obj.respond_to?(:each)
obj.each { |obj| identify(obj) }
end
end
def logger
RAILS_DEFAULT_LOGGER
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment