簡體   English   中英

使用回形針將對象與S3上的現有文件相關聯

[英]Associate object to pre-existing file on S3, using Paperclip

我已經在S3上擁有一個文件,希望將其關聯到Asset模型的現有實例。

這是模型:

class Asset < ActiveRecord::Base
  attr_accessible(:attachment_content_type, :attachment_file_name,
                 :attachment_file_size, :attachment_updated_at, :attachment)

  has_attached_file :attachment, {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: ":class/:attachment/:id_partition/:style/:filename",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
end

假設路徑為assets/attachments/000/111/file.png ,而我要與該文件關聯的Asset實例為asset 源頭引用,我嘗試過:

options = {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: "assets/attachments/000/111/file.png",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
# The above is identical to the options given in the model, except for the path

Paperclip::Attachment.new("file.png", asset, options).save

據我所知,這絲毫沒有影響asset 我無法手動設置asset.attachment.path

關於SO的其他問題似乎並未專門解決。 無法在我設置的路徑中保存回形針圖像 ”,“ Paperclip和Amazon S3如何執行路徑? ”,等等,包括建立模型,這已經可以正常工作了。

有人有什么見識嗎?

據我所知, 確實需要按照@ oregontrail256的建議將S3對象轉換為File 我使用了Fog gem來做到這一點。

s3 = Fog::Storage.new(
        :provider => 'AWS',
        :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
        :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
      )

directory = s3.directories.get(ENV['S3_BUCKET_NAME'])
fog_file = directory.files.get(path)

file = File.open("temp", "wb")
file.write(fog_file.body)
asset.attachment = file
asset.save
file.close

回形針附件具有copy_to_local_file()方法,該方法使您可以創建附件的本地副本。 那么呢:

file_name = "temp_file"
asset1.attachment.copy_to_local_file(:style, file_name)
file = File.open(file_name)
asset2.attachment = file
file.close
asset2.save!

即使銷毀asset1,您現在也擁有資產2單獨保存的附件的副本。 如果您要執行許多操作,則可能需要在后台執行此操作。

也要相信這個答案: 如何使用Paperclip以編程方式設置文件上傳

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM