在Rails中保存视频文件

时间:2014-10-01 01:35:21

标签: ruby-on-rails file video attachment

好的,所以我过去使用过paperclip上传图片和视频。我在想。是否有一种简单的方法可以将视频保存在rails中?我已经找到了上传文件的表格,我想知道是否有某种类型我应该保存它。 (显然不是字符串,而是沿着那些线。)我只想拥有一个包含所有三种文件类型的视频播放器。 (ogg,mp4,wav)。只是每一个都保存在数据库中自己的行中。

1 个答案:

答案 0 :(得分:4)

您可能想要查看paperclip-ffmpeg。我会将不同的格式保存为回形针样式。这应该与典型的回形针图像上传非常相似,您可以在此处理图像以生成不同的尺寸,例如 thumbnail

免责声明:通过这种方式,您需要在服务器上安装ffmpeg。如果您使用的是Mac并使用自制程序,则此链接很有帮助。 http://www.renevolution.com/how-to-install-ffmpeg-on-mac-os-x/

在下面的示例中,我们假设您的数据库中的文件附件设置为data

运行迁移以将适当的列添加到表中。

> rails g migration add_data_to_videos data:attachment

然后在你的模特中。

# Validations
validates_attachment_presence :data
validates_attachment_size :data, less_than: 100.megabytes # if you want a max file size
validates_attachment_content_type :data, content_type: /\Avideo\/.*\Z/ # or you can specify individual content types you want to allow

has_attached_file :data,
  url: '/videos/:id/:style/:basename.:extension', # whatever you want
  styles: {
    poster: { size: '640x480', format: 'jpg' }, # this takes a snapshot of the video to have as your poster
    v_large_webm: { geometry: '640x480', format: 'webm' }, # your webm format
    v_large_mp4: { geometry: '640x480', format: 'mp4' } # your mp4 format
  },
  processors: [:ffmpeg],
  auto_rotate: true

使用此设置,您的视图将非常类似于使用带有图像的回形针。

# To display the video (HTML5 way using HAML)
%video{controls: '', height: 'auto', width: '100%', poster: @video.data.url(:poster)}
  %source{src: @video.data.url(:v_large_mp4), type: 'video/mp4'}
  %source{src: @video.data.url(:v_large_webm), type: 'video/webm'}
    Your browser does not support the video tag.

我还建议您考虑使用后台作业来进行处理。也许是DelayedJob。