【问题标题】:setting content-type for mp4 files on s3在 s3 上设置 mp4 文件的内容类型
【发布时间】:2012-07-22 05:45:09
【问题描述】:

我正在借助回形针 gem 和 s3 存储将用户上传的视频添加到我的 RoRs 网站。由于某种我无法弄清楚的原因,每当用户上传 mp4 文件时,s3 将该文件的内容类型设置为 application/mp4 而不是 video/mp4

请注意,我已经在初始化文件中注册了 mp4 mime 类型:

Mime::Type.lookup_by_extension('mp4').to_s => "video/mp4"

这是我的 Post 模型的相关部分:

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

  validates_attachment_content_type :video,
     :content_type => ['video/mp4'],
     :message => "Sorry, this site currently only supports MP4 video"

我的回形针和/或 s3 设置中缺少什么。

####Update#####

由于某些超出我对 Rails 知识范围的原因,我对包含 mp4 的文件的默认 mime 类型如下:

    MIME::Types.type_for("my_video.mp4").to_s
 => "[application/mp4, audio/mp4, video/mp4, video/vnd.objectvideo]" 

因此,当回形针将 mp4 文件发送到 s3 时,它似乎将文件的 mime 类型识别为第一个默认值“application/mp4”。这就是为什么 s3 将文件标识为内容类型为“application/mp4”的原因。因为我想启用这些 mp4 文件的流式传输,所以我需要回形针来将文件识别为具有“video/mp4”的 mime 类型。

有没有办法修改回形针(可能在 before_post_process 过滤器中)以允许这样做,或者有没有办法通过 init 文件修改 rails 以将 mp4 文件标识为“video/mp4”。如果我可以做任何一个,哪种方式最好。

感谢您的帮助

【问题讨论】:

  • .svg 上传也有类似问题。这解决了我的问题: :s3_headers => { "Content-Type" => "image/svg+xml" }

标签: ruby-on-rails amazon-s3 paperclip


【解决方案1】:

我做了以下事情:

...
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
...

【讨论】:

    【解决方案2】:

    原来我需要在模型中设置一个默认的 s3 标头 content_type。这对我来说不是最好的解决方案,因为在某些时候我可能会开始允许 mp4 以外的视频容器。但它让我继续处理下一个问题。

      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" }
    

    【讨论】:

      猜你喜欢
      • 2014-03-15
      • 1970-01-01
      • 2021-07-26
      • 2014-11-05
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      相关资源
      最近更新 更多