【问题标题】:Rename files before uploading to S3在上传到 S3 之前重命名文件
【发布时间】:2016-09-21 16:08:14
【问题描述】:

我的 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

宝石文件:

gem 'aws-sdk', '< 2.0'
gem 'paperclip'

我尝试在回调之前/之后使用回形针,但它们似乎没有为我提供提交的表单字段数据。我喜欢 s3_direct_upload gem 的想法,但我不确定它是否会起作用,因为它似乎没有在积极开发中

非常感谢任何帮助。

从长远来看,我希望允许用户使用带有某种进度条的 AJAX 进行多次上传。

【问题讨论】:

    标签: ruby-on-rails-4 amazon-s3 paperclip aws-sdk


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 1970-01-01
      • 2014-12-19
      • 2019-10-22
      • 2020-01-23
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多