Rails使用carrierwave gem上传视频和图像

时间:2018-10-12 08:42:42

标签: ruby-on-rails carrierwave

我正在使用carrierwave gem来上传视频和图像。一切正常,如您所见,图像和视频均已保存:

enter image description here

但是,当我将视频放置在video_tag内时,在控制台ActionController::RoutingError (No route matches [GET] "/uploads/attachment/media_files/8/SampleVideo_1280x720_1mb.mp4"):和以下无法播放的视频中出现了此错误。

enter image description here

相反,它应该能够播放视频并显示预览缩略图。

这是我的设置:

gem 'carrierwave'
gem 'carrierwave-video'
gem 'mime-types'
gem "rmagick"
gem 'carrierwave-video-thumbnailer'
gem 'mini_magick'


class AttachmentUploader < CarrierWave::Uploader::Base
after :store, :remove_original_file

def remove_original_file(p)
  if self.version_name.nil?
    self.file.delete if self.file.exists?
  end
end

include CarrierWave::RMagick
include CarrierWave::Video
include CarrierWave::FFmpeg
include CarrierWave::Video::Thumbnailer



def set_content_type
  model.content_type = content_type
end


storage :file


def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end


process :set_content_type

def auto_orient
  manipulate! do |img|
    img = img.auto_orient
  end
end


def size_range
  0..15.megabytes
end


version :video, :if => :video? do
  process :encode
  process encode_video: [:mp4, callbacks: { after_transcode: :set_success } ]
end

version :thumb do
  process thumbnail: [{format: 'jpg', quality: 8, size: 360, logger: Rails.logger}]
  def full_filename for_file
    jpg_name for_file, version_name
  end
end

version :medium do
  process thumbnail: [{format: 'jpg', quality: 85, size: 300, logger: Rails.logger}]
  def full_filename for_file
    jpg_name for_file, version_name
  end
end

version :thumb_image,:if => :image? do
  process :auto_orient
  process :resize_to_fit => [640, 400]
end

version :mini_image,:if => :image? do
  process :auto_orient
  process :resize_to_fit => [100, 100]
end

def jpg_name for_file, version_name
  %Q{#{version_name}_#{for_file.chomp(File.extname(for_file))}.jpg}
end

def encode
  video = FFMPEG::Movie.new(@file.path)
  video_transcode = video.transcode(@file.path)
end

def extension_whitelist
  %w(mp4 jpg jpeg gif png)
end

protected
def image?(new_file)
  new_file.content_type.include? 'image'
end
def video?(new_file)
  new_file.content_type.include? 'video'
end
end

附件模型:

mount_uploader :media_files, AttachmentUploader

这是我在视图内获取文件的方式:

<% unless @attachments.blank? %>
<% @attachments.each do |attachment| %>
<%= image_tag attachment.media_files_url(:mini_image).to_s if attachment.content_type == 'image/jpeg' %>
<%= video_tag attachment.media_files_url(:video).to_s, :controls => true if attachment.content_type == 'video/mp4' %>
<% end %>
<% end %>

关于如何进行这项工作的任何想法?

0 个答案:

没有答案