好的,这是一个复杂的,但它是可行的。这是我如何让它工作的。
在客户端,我使用了 http://github.com/valums/file-uploader,这是一个 javascript 库,它允许通过进度条和拖放支持上传多个文件。它得到很好的支持、高度可配置且基本实现很简单:
在视图中:
<div id='file-uploader'><noscript><p>Please Enable JavaScript to use the file uploader</p></noscript></div>
在js中:
var uploader = new qq.FileUploader({
element: $('#file-uploader')[0],
action: 'files/upload',
onComplete: function(id, fileName, responseJSON){
// callback
}
});
当提交文件时,FileUploader 将它们作为 XHR 请求发布到服务器,其中 POST 正文是原始文件数据,而标题和文件名在 URL 字符串中传递(这是通过 javascript 异步上传文件的唯一方法)。
这是复杂的地方,因为 Paperclip 不知道如何处理这些原始请求,您必须捕获并将它们转换回标准文件(最好在它们到达您的 Rails 应用程序之前),以便 Paperclip 可以工作魔法。这是通过一些创建新临时文件的机架中间件完成的(记住:Heroku 是只读的):
# Embarrassing note: This code was adapted from an example I found somewhere online
# if you recoginize any of it please let me know so I pass credit.
module Rack
class RawFileStubber
def initialize(app, path=/files\/upload/) # change for your route, careful.
@app, @path = app, path
end
def call(env)
if env["PATH_INFO"] =~ @path
convert_and_pass_on(env)
end
@app.call(env)
end
def convert_and_pass_on(env)
tempfile = env['rack.input'].to_tempfile
fake_file = {
:filename => env['HTTP_X_FILE_NAME'],
:type => content_type(env['HTTP_X_FILE_NAME']),
:tempfile => tempfile
}
env['rack.request.form_input'] = env['rack.input']
env['rack.request.form_hash'] ||= {}
env['rack.request.query_hash'] ||= {}
env['rack.request.form_hash']['file'] = fake_file
env['rack.request.query_hash']['file'] = fake_file
if query_params = env['HTTP_X_QUERY_PARAMS']
require 'json'
params = JSON.parse(query_params)
env['rack.request.form_hash'].merge!(params)
env['rack.request.query_hash'].merge!(params)
end
end
def content_type(filename)
case type = (filename.to_s.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
when %r"jp(e|g|eg)" then "image/jpeg"
when %r"tiff?" then "image/tiff"
when %r"png", "gif", "bmp" then "image/#{type}"
when "txt" then "text/plain"
when %r"html?" then "text/html"
when "js" then "application/js"
when "csv", "xml", "css" then "text/#{type}"
else 'application/octet-stream'
end
end
end
end
稍后,在 application.rb 中:
config.middleware.use 'Rack::RawFileStubber'
然后在控制器中:
def upload
@foo = modelWithPaperclip.create({ :img => params[:file] })
end
这很可靠,但同时上传大量文件时可能会很慢。
免责声明
这是针对具有单个、已知且受信任的后端用户的项目实施的。几乎可以肯定,它对高流量 Heroku 应用程序有一些严重的性能影响,我还没有对它进行安全测试。也就是说,它确实有效。