setting content-type for mp4 files on s3

家住魔仙堡 提交于 2019-11-29 14:14:44

Turns out that I needed to set a default s3 header content_type in the model. This isn't the best solution for me because at some point I might start allowing video containers other than mp4. But it gets me moving on to the next problem.

  has_attached_file :video, 
                :storage => :s3,
                :s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
                :path => "/video/:id/:filename",
                :s3_headers =>  { "Content-Type" => "video/mp4" }

I did the following:

...
MIN_VIDEO_SIZE = 0.megabytes
MAX_VIDEO_SIZE = 2048.megabytes
VALID_VIDEO_CONTENT_TYPES = ["video/mp4", /\Avideo/] # Note: The regular expression /\Avideo/ will match anything that starts with "video"

has_attached_file :video, {
  url: BASE_URL,
  path: "video/:id_partition/:filename"
}

validates_attachment :video,
    size: { in: MIN_VIDEO_SIZE..MAX_VIDEO_SIZE }, 
    content_type: { content_type: VALID_VIDEO_CONTENT_TYPES }

before_validation :validate_video_content_type, on: :create

before_post_process :validate_video_content_type

def validate_video_content_type
  if video_content_type == "application/octet-stream"
    # Finds the first match and returns it. 
    # Alternatively you could use the ".select" method instead which would find all mime types that match any of the VALID_VIDEO_CONTENT_TYPES
    mime_type = MIME::Types.type_for(video_file_name).find do |type| 
      type.to_s.match Regexp.union(VALID_VIDEO_CONTENT_TYPES)
    end

    self.video_content_type = mime_type.to_s unless mime_type.blank?   
  end
end
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!