ruby-on-rails - Paperclip 在 Rails 中将图像上传到 S3。文件上传速度非常慢。解决方法?

标签 ruby-on-rails amazon-s3 paperclip delayed-job swfupload

我正在开发一个 Rails 应用程序,用户将在其中上传大量图像。

我当前的设置:使用带有 S3 存储的 Paperclip 插件,使用 SWFUpload 一次上传多个文件。原图上传到S3后,Delayed_Job用于后期处理(缩略图等)。

我遇到的问题是图片上传速度非常慢。我假设默认的 Paperclip 设置是图像将从用户到 -> 我的服务器到 -> s3。

我想我可以将图像直接上传到 s3,但我不确定如何使用 Paperclip 和后期处理来实现它。我找不到任何处理此问题的插件或示例。

有人有什么建议吗?如果没有,您能指出正确的方向吗?

提前致谢!

蒂姆

最佳答案

同样的问题我遇到过几次。我解决它的方法是创建 2 个模型,一个 Image模型和一个 TempImage模型,继承自 Image模型。这需要你有一个 type您的 Image 上的专栏 table 。 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模型应始终包含您的后期处理,因为这将在后台完成。

您始终可以覆盖一些方法以使其更简洁一些,但这可以让您更好地了解它是如何工作的以及您需要做什么才能让它按您希望的方式工作。

关于ruby-on-rails - Paperclip 在 Rails 中将图像上传到 S3。文件上传速度非常慢。解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656091/

相关文章:

amazon-web-services - 使用S3上传但不允许公共(public)访问

ruby - 通过在特定路径配置上使用带有 "s3"的 Paperclip 获得 S3::Error::SignatureDoesNotMatch

java - HTTP-POST 图像到 Ruby on Rails 应用程序

ruby-on-rails - 我不知道我使用的是哪个版本的 Ruby

ruby-on-rails - Net::HTTP::Get 超时问题

amazon-web-services - 将通配符子域映射到 S3 静态站点文件夹

ruby-on-rails - Rails 视频上传

python - Ruby 和 Python 中发生了什么?为什么变量在 ruby​​ 的 if block 中为 nil,而在 python 中为 undefined?

ruby-on-rails - rails : Store GPS coordinates with new record

amazon-web-services - 在 Route 53 中将裸域重定向到 WWW