Jun'uary
Jan'uary » 日志 » Use Merb to handle file upload for Rails
Use Merb to handle file upload for Rails
Jan 发表于 2008-08-19 15:27:45
As you know Rails does bad on handling file upload, a large file will block your Rails app a long while, make it busy on receiving the file and can't give response to other visitors, make them upset and leave you alone.
One solution is using merb to handle file upload for rails. The latest Merb that build on Rack(a cool framework who help you dealing with all kinds of http servers) does a really good job on uploading.
First, install merb:
Second, create a merb app in your rails dir:
You can ignore all other files except config/rack.rb, this is the only file we need to modify. Currently there's only one line in the file:
this line will ask merb to handle the http request come from rack. Let us change this:
At last, run merb up ("merb -p 1234 -c 1 -e production -d") and config your apache/whatever to redirect all request to /uploader to port 1234(Your merb uploader is listening here!).
Pretty easy, isn't it?
One solution is using merb to handle file upload for rails. The latest Merb that build on Rack(a cool framework who help you dealing with all kinds of http servers) does a really good job on uploading.
First, install merb:
sudo gem i merb
Second, create a merb app in your rails dir:
merb-gen app uploader
cd uploader
You can ignore all other files except config/rack.rb, this is the only file we need to modify. Currently there's only one line in the file:
run Merb::Rack::Application.new
this line will ask merb to handle the http request come from rack. Let us change this:
require 'cgi'
class File
def to_s
path
end
end
# build a new handler to handler rack's request
class Uploader
def call(env)
# leverage merb's utility to parse the request.
# Merb will save the file to a tempfile and save the tempfile's path in request's param
request = Merb::Request.new(env)
params = request.params
# pass the params directly to the real (rails) app
result = post("http://someplace.com/api", hash_to_params(params)).split("\n")[-1]
# processing result or just ignore it ...
end
private
def post(url, params="")
curl_cmd = "curl -H \"Content-type: application/x-www-form-urlencoded\" #{url} -d \"#{params}\""
puts "curl_cmd = #{curl_cmd}"
f = IO.popen(curl_cmd +" 2>&1")
result = f.read
f.close
result
end
def hash_to_params(hash)
hash.map do |k, v|
if v.kind_of? Hash
h = {}
v.each { |kk, vv| h["#{k}[#{kk}]"] = vv }
hash_to_params h
else
"#{k}=#{CGI.escape v.to_s}"
end
end.join("&")
end
end
run Uploader.new
At last, run merb up ("merb -p 1234 -c 1 -e production -d") and config your apache/whatever to redirect all request to /uploader to port 1234(Your merb uploader is listening here!).
Pretty easy, isn't it?
曾经的这一天...
- » 2005年: Google Guide
相关日志:
收藏:
QQ书签
del.icio.us
订阅:
Google
抓虾
