2010-09-07 84 views
3

我正在使用Rails應用程序,用戶將上傳大量圖像。回形針在Rails中將圖像上傳到S3。文件上傳速度非常慢。解決方法?

我目前的設置:使用SWFUpload使用帶有S3存儲的Paperclip插件一次上傳多個文件。在原始圖像上傳到S3後,Delayed_Job用於後期處理(縮略圖等)。

我遇到的問題是圖像上傳速度很慢。我假設默認的Paperclip設置是圖像將從用戶到 - >我的服務器到 - > s3。

我在想我可以將圖片直接上傳到s3,但我不確定如何使用回形針和後期處理來實現。我找不到任何插件或例子來處理這個問題。

有沒有人有什麼建議?如果不是,你能指出我的方向嗎?

提前致謝!

Tim

回答

3

我已經跑了幾次這個相同的問題。我解決這個問題的方式是創建2個模型,一個Image模型和一個TempImage模型,它繼承了Image模型。這要求您在Image表上有type列。 TempImage模型將圖像保存到本地,然後當您直接從Image模型訪問它並重新保存它時,它將遵循Image模型中定義的任何內容,即Amazon S3。

例子:

# Will save in the database as a TempImage inside the Image table 
temp = TempImage.create(:asset => File.new('some_path', 'r')) 

# When you find it again through the Image model, it bypasses the type column 
# so next time you save it, it is saved as an Image. 
amazon = Image.find(temp.id) 
amazon.save! 

這是我的工作延遲:

class MoveToS3Job < Struct.new(:temp_revision_id) 
    def perform 
    upload = Image.find(temp_revision_id) 
    temp_path = File.expand_path("tmp/uploads/#{upload.asset_file_name}", Rails.root) 
    upload.asset = File.new(temp_path, 'r') 
    upload.save! 

    if File.exists?(temp_path) && !File.directory?(temp_path) 
     File.delete(temp_path) 
    end 
    rescue ActiveRecord::RecordNotFound 
    # If the record wasn't found, do some sort of 
    # error report, but don't keep it in the queue. 
    end 
end 

這裏是TempImage型號:

class TempImage < Image 
    has_attached_file :asset, { 
    :path => ":rails_root/tmp/uploads/:basename_:updated_at.:extension" 
    } 
end 

那麼原來Image型號:

class Image < ActiveRecord::Base 
    # Validations 
    validates :asset, :presence => true 

    # Paperclip 
    has_attached_file :asset, :styles => { 
    :preview => ['100x100#', :png], 
    :thumb => ['50x50#', :png] 
    }, 
    :default_style => :thumb, 
    :storage => :s3, 
    :bucket => 'bucket-name', 
    :s3_credentials => File.expand_path('config/s3.yml', Rails.root), 
    :path => "photos/:id_partition/:style.:extension" 
end 

您的原始Image模型應始終包含您的後處理,因爲這將在後臺完成。

您可以隨時覆蓋一些方法使其更清潔一些,但這會讓您更好地瞭解它是如何工作的以及您需要做什麼,以便您可以按照自己的需要進行工作。

0

如果你最終會從您的Rails服務器卸載工作直接上傳到S3的路線,請查看我的樣本項目:

示例項目使用Rails 3,Flash和基於MooTools的-FancyUploader上傳直接到S3:https://github.com/iwasrobbed/Rails3-S3-Uploader-FancyUploader

使用Rails 3 Sample項目,閃存/ Silverlight的/ GoogleGears /的BrowserPlus和基於jQuery的Plupload直接上傳到S3:https://github.com/iwasrobbed/Rails3-S3-Uploader-Plupload

順便說一句,你可以做後期處理回形針使用這樣的博客文章d escribes:

http://www.railstoolkit.com/posts/fancyupload-amazon-s3-uploader-with-paperclip