問題描述
無法使用 S3 圖像的 image.to_file 使用 Paperclip gem 複製圖像 (Can't copy images with Paperclip gem using image.to_file for S3 images)
我遇到的問題僅在其生產環境中影響此應用程序。我們有一個控制器動作,用於通過創建一個新對象、將屬性設置為彼此相等、然後將圖像添加到對象來“克隆”文章對象。
這是正在這樣做的控制器:
def clone_article
ba = BlogArticle.find(params[:id])
new_ba = BlogArticle.new(ba.attributes)
ba.blog_article_images.each do |blog_img|
new_ba.blog_article_images.build(:image => blog_img.image.to_file, :embedded => blog_img.embedded?)
end
new_ba.status = 'draft'
new_ba.title = "Copy of #{ba.title}"
if new_ba.save
flash[:notice] = "Clone successful"
else
if new_ba.errors.empty?
flash[:notice] = "Unknown error occurred while cloning the post"
else
error = 'Problem while cloning the post: <br>'
new_ba.errors.each {|field, msg| error += field + " " + msg + "<br>"}
flash[:error] = error
end
end
redirect_to admin_blog_articles_url
end
問題是這個腳本在引用服務器上的本地文件時可以完美運行。但是在 S3 上有圖像的生產環境中,我們無法從原始帖子圖像中復制任何圖像。我認為這可能是時間問題,例如控制器在完成過程之前沒有等待回形針完成將文件加載到應用程序目錄中,但我似乎無法進行任何工作。另外,我不是 Rails 專家,所以我有點迷路了。
謝謝
參考解法
方法 1:
I've run into the issue with filenames getting mangled by Tempfile
as well, and ended up with this somewhat hackish solution:
ba.blog_article_images.each do |blog_img|
new_img = blog_img.image.to_file
new_img.instance_variable_set("@original_filename", blog_img.image.original_filename)
def new_img.original_filename
@original_filename
end
new_ba.blog_article_images.build(:image => new_img, :embedded => blog_img.embedded?)
end
it does work though. original_filename
is a method that Paperclip adds to File
, and we're just overriding it here.
I haven't tested this with a local storage, but from reading the Paperclip source, it should work.
方法 2:
I'm working on something similar. I've found that simply doing object_2.file = object_1.file, then saving object_2 works fine. Mostly. The S3 transfer works dandy but the filename is getting mangled for some unknown reason.
方法 3:
The file gets mangled because the file from object_1 is copied down from S3 and stored as a TempFile which makes it's own file name using the original file name at the start and extension at the end. I'm working on this same problem too and appreciate any thoughts on how to change the TempFile name before saving object_2.
(by John、AlexT、uberllama、hkelsey)