简体   繁体   English

使用Paperclip / Rails为AWS S3正确设置URL / PATH

[英]Setting URL/PATH correctly for AWS S3 by using Paperclip/Rails

I have two models: Collection and Letter . 我有两个模型: CollectionLetter Collection has many Letter s and Letter obviously belongs_to Collection . Collection有很多Letter并且Letter显然属于Collection

Below is my Letter.rb file: 以下是我的Letter.rb文件:

class Letter < ActiveRecord::Base
    belongs_to :collection

    has_attached_file :pdf,
                    :url => "/pdf/:id/:style/:basename.:extension",
                    :path => "/pdf/:id/:style/:basename.:extension",
                    :s3_host_name => host_name,
                    :storage => :s3,
                    :bucket  => ENV['S3_BUCKET_NAME'],
                    :s3_credentials => {
                                        :access_key_id =>#ENV['AWS_ACCESS_KEY_ID'],
                                        :secret_access_key =>ENV['AWS_SECRET_ACCESS_KEY']
                                    }

    validates_attachment :pdf,
                     :content_type => {
                         :content_type =>
                             ["application/pdf", "text/plain", /\Aimage\/.*\Z/, "application/msword"]
                     }

end

I have a question about url and path attribute in has_attached_file . 我对has_attached_file urlpath属性有疑问。

Instead of setting letter model's id in path, I would like to set collection's id. 我不想在路径中设置字母模型的ID,而是要设置集合的ID。 Additionally, I also wanna put title which is Letter's attribute. 另外,我也想把title作为Letter的属性。 Let's say @collection 's id is 1. @collection has @letter1 and @letter2. 比方说, @collection的ID为1 @collection有@ letter1和@ letter2。 When I save the files to AWS S3, I want to save it under /pdf/1(which is collection_id)/:title . 将文件保存到AWS S3时,我想将其保存在/pdf/1(which is collection_id)/:title How can I write this in url and path ? 如何在urlpath编写此内容?

In Paperclip, you can use interpolations for that. 在回形针中,您可以使用插值法。

Your has_attached_file method would look somewhat like this; 你的has_attached_file方法看起来像这样;

has_attached_file :image, :default_url => "/pdf/:collection_id/:title/:basename.:extension"

Create an interpolation file, called paperclip.rb or interpolations.rb in the config/initializers directory (rails picks up any script in that folder on startup), which contains code that looks somewhat like this; config/initializers目录中创建一个名为paperclip.rbinterpolations.rb的插值文件(rails在启动时会拾取该文件夹中的任何脚本),其中包含类似于以下代码的代码;

Paperclip.interpolates :collection_id do |attachment, style|
    attachment.instance.collection_id
end

Add the :title interpolation in the same way; 以相同的方式添加:title插值; add it to your has_attached_file urls, and create a second interpolation for that. 将其添加到您的has_attached_file网址中,并为此创建第二个插值。

You can read more about this at https://github.com/thoughtbot/paperclip/wiki/Interpolations 您可以在https://github.com/thoughtbot/paperclip/wiki/Interpolations上了解更多信息

In your case, I would suggest to also include the :id of the Letter in the URL, as it might be possible the user uploads two documents with the same title which might conflict. 对于您的情况,我建议在URL中也包含Letter的:id,因为用户可能会上传两个标题相同的文档,这可能会产生冲突。

has_attached_file :image, :default_url => "/pdf/:collection_id/:id/:title"

Paperclip uses the interpolations :basename , :extension and :style by default to create a unique path for the file. 回形针默认使用插值:basename:extension:style为文件创建唯一路径。

  • :basename is the base file name of the uploaded file :basename是上载文件的基本文件名
  • :extension is the extension of that uploaded file :extension是该上传文件的扩展名
  • :style is the "style" or size of that uploaded file :style是该上传文件的“样式”或大小

You can specify multiple styles (like thumnails in various versions). 您可以指定多种样式(例如各种版本的缩略图)。 The default style is "original", which will contain the original uploaded file. 默认样式为“原始”,它将包含原始上载的文件。

Read more about styles here; 在此处阅读有关样式的更多信息; https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation https://github.com/thoughtbot/paperclip/wiki/缩略图生成

Always try to keep the original file as it can be handy in the future; 始终尝试保留原始文件,以备将来使用。 when your site/application layout changes and new thumbnail sizes are required. 当您的网站/应用程序布局更改并且需要新的缩略图大小时。 You can rebuild/regenerate your whole thumbnail library from the original version. 您可以从原始版本重建/重新生成整个缩略图库。

Read more about generating/regenerating thumbnails here; 在此处阅读有关生成/重新生成缩略图的更多信息。 https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation#generatingregenerating-your-thumbnails https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation#generatingregenerating-your-thumbnails

Using gem aws-sdk for a ror application for uploading images to s3 Uploading images to a fixed bucket with different folders for each object or application. 将gem aws-sdk用于ror应用程序以将图像上载到s3将图像上载到具有每个对象或应用程序不同文件夹的固定存储桶。 The s3 keeps a limitation on the number of buckets creattion whereas there is no limitation for content inside a bucket. s3限制了存储桶创建的数量,而存储桶内的内容没有限制。

This code will upload image for a user to s3 using aws-sdk gem. 此代码将使用aws-sdk gem将用户的图片上传到s3。 The bucket and the image uploaded are made public so that the images uploaded are directly accessible. 将存储桶和上传的图像公开,以便直接访问上传的图像。 The input it takes is the image complete path where it is present, folder in which it should be uploaded and user_id for whom it should be uploaded. 输入的内容是图像的完整路径,要上传图像的文件夹以及要为其上传图像的user_id。

  def save_screenshot_to_s3(image_location, folder_name,user_id)
    service = AWS::S3.new(:access_key_id => ACCESS_KEY_ID,
                          :secret_access_key => SECRET_ACCESS_KEY)
    bucket_name = "app-images"
    if(service.buckets.include?(bucket_name))
      bucket = service.buckets[bucket_name]
    else
      bucket = service.buckets.create(bucket_name)
    end
    bucket.acl = :public_read
    key = folder_name.to_s + "/" + File.basename(image_location)
    s3_file = service.buckets[bucket_name].objects[key].write(:file => image_location)
    s3_file.acl = :public_read
    user = User.where(id: user_id).first
    user.image = s3_file.public_url.to_s
    user.save
  end   

Use key = folder_name.to_s + "/" + File.basename(image_location) to customize the path you want to have. 使用key = folder_name.to_s +“ /” + File.basename(image_location)来定制您想要的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM