我无法弄清楚如何在rails 3.2.6中更新/重命名使用Carrierwave-mongoid上传/管理的文件。我想重命名数据库中的文件以及文件系统。
这样的事可能......
def rename( id , new_name )
f = UploadedFile.find(id)
if f.update_attributes({ f.file.original_filename: new_name }) # this is WRONG, what is right???
new_path = File.join( File.dirname( f.file.current_path ) , new_name ))
FileUtils.mv( f.file.current_path , new_path )
end
return f
end
让我在已经上传之后添加它。
答案 0 :(得分:4)
我能够得到以下工作,虽然我确信有更优雅的方式。我很感激以下任何评论
*将此添加到app / uploaders / file_uploader.rb
def rename(new_name)
sf = model.file.file
new_path = File.join( File.dirname( sf.file ) , "#{new_name}#{File.extname( sf.file )}")
new_sf = CarrierWave::SanitizedFile.new sf.move_to(new_path)
model.file.cache!(new_sf)
model.save!
return model
end
谢谢!
答案 1 :(得分:0)
我在上传程序文件中修改版本设置(文件名和图像大小)后,使用此rake任务重新处理上传的图像:
# Usage: rake carrierwave:reprocess class=Model
namespace :carrierwave do
task :reprocess => :environment do
CLASS = ENV['class'].capitalize
MODEL = Kernel.const_get(CLASS)
records = MODEL.all
records.each do |record|
record.photo.recreate_versions! if record.photo?
end
end
end
注意:
答案 2 :(得分:0)
基于@ user892583,我研究了它并提出了一个更简单的解决方案:
def rename!(new_name)
new_path = File.join(File.dirname(file.file), new_name)
file.move_to(new_path)
end
答案 3 :(得分:0)
我是这样做的:
def filename
if !cached? && file.present?
new_filename = 'foobar'
new_path = File.join(File.dirname(file.path), new_filename)
file.move_to(new_path)
recreate_versions!
new_filename
else
super
end
end
我认为这只是重命名文件的正确方法。
答案 4 :(得分:0)
最有效的方法是仅移动现有的S3对象(假设您的存储层为S3):
def rename(new_name)
bucket_name = "yourapp-#{Rails.env}"
resource = Aws::S3::Resource.new
bucket = resource.bucket(bucket_name)
object = bucket.object(path)
new_filename = "#{new_name}#{File.extname(path)}"
new_path = File.join(File.dirname(path), new_filename)
object.move_to(bucket: bucket_name, key: new_path)
model.update_column(mounted_as, new_filename)
model.reload
# Now call `recreate_versions!(*versions.keys)`
# if you want versions updated. Explicitly passing
# versions will prevent the base version getting
# reuploaded.
model
end
这是使用aws-sdk-s3
宝石。
答案 5 :(得分:0)
我将图像文件和衍生版本存储在S3兼容解决方案中。我在Rails 5.1上将Carrierwave(1.2.2)与“ fog-aws” gem(3.0.0)结合使用。将以下公共方法添加到“上载器”文件(例如app/uploaders/example_uploader.rb
)后对我有用:
class ExampleUploader < CarrierWave::Uploader::Base
<snip>
# Renames original file and versions to match given filename
#
# Options:
# * +:keep_original+ - Do not remove original file and versions (ie, copy only)
def rename(new_filename, options = {})
return if !file || new_filename == file.filename
target = File.join(store_path, new_filename)
file.copy_to(target)
versions.keys.each do |k|
target = File.join(store_path, "#{k}_#{new_filename}")
version = send(k).file
version.copy_to(target)
end
remove! unless options[:keep_original]
model.update_column(mounted_as, new_filename) && model.reload
end
<snip>
end