我的rails应用程序已将用户选择的上传文件保存到AWS S3。用户在表单上填写与他们即将上传的文件相关的几个字段。我需要使用该信息来构造新的文件名。
这是模型:
class DocAttachment < ActiveRecord::Base
belongs_to :doc_attachment_type
belongs_to :language
has_attached_file :attachment
before_save :rename_file
#Attempted Paperclips callbacks but couldn't get values for the form
#after_attachment_post_process :rename_file
validates_attachment_presence :attachment
validates_attachment_content_type :attachment,
content_type: %w(application/pdf application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document text/plain),
size: { :in => 0..10.megabytes }
validates :doc_attachment_type_id, presence: true
validates :code, presence: true
validates :title, presence: true
validates :language_id, presence: true
def rename_file
extension = File.extname(attachment_file_name).gsub(/^\.+/, '')
filename = attachment_file_name.gsub(/\.#{extension}$/, '')
new_attachment_file_name = "#{self.code}-#{self.language.name}.#{extension}"
attachment.instance_write(:attachment_file_name, new_attachment_file_name)
end
end
的Gemfile:
gem 'aws-sdk', '< 2.0'
gem 'paperclip'
我试图在回调之前/之后使用回形针,但它们似乎没有向我提供提交的表单字段数据。我喜欢s3_direct_upload gem的想法,但我不确定它是否会起作用,因为它似乎没有处于活动开发状态
非常感谢任何帮助。
从长远来看,我想允许用户使用某种进度条使用AJAX进行多次上传。
答案 0 :(得分:1)
问题出在rename_file方法的最后一行。
def rename_file
extension = File.extname(attachment_file_name).gsub(/^\.+/, '')
filename = attachment_file_name.gsub(/\.#{extension}$/, '')
new_attachment_file_name = "#{self.code}-#{self.language.name}.#{extension}"
attachment.instance_write(:file_name, new_attachment_file_name)
end