使用载波在Rails视图中加载图像和视频

基思

问题是,如果我上传的图片显示了2次图片(一次在video_tag中,另一次在 image_tag

所以我试图使图像仅出现在 image_tag

<%= video_tag @post.file :controls =>true if @post.file? %>
<%= image_tag @post.file.url if @post.file? %>
7urkm3n

您有很多选择可以做到。首先尝试使用Rails助手。

Rails版本:

#app/helpers/application_helper.rb
module ApplicationHelper
    def file_type(filename)
       types = {
         :jpeg => "image",
         :jpg => "image",
         :gif => "image",
         :png => "image",
         :mp4 => "video", 
         :mkv => "video"
       }
       types[filename.split(".").last.to_sym]
    end
end

#html page
<% if @post.file? %>
     <% type = file_type(@post.file.url)%>
     <% if type == 'image' %>
         <%= image_tag @post.file.url %>
     <% elsif type == 'video' %>
         <%= video_tag @post.file :controls =>true %>
     <% end %>
<% end %>

另外,您可以使用javascript来实现。

#html page
#remove these lines
#<%= video_tag @post.file :controls =>true if @post.file? %>
#<%= image_tag @post.file.url if @post.file? %>

#add this div empty
<div id='dynamic_file_load'></div>


<script>
  types = {
    ".jpg": "image",
    ".jpeg": "image",
    ".gif": "image",
    ".png": "image",
    ".mp4": "video", 
    ".mkv": "video"
  }

  function checkeExtension(filename) {
      var re = /\..+$/;
      var ext = filename.match(re);
      if (types[ext] == 'video') {
         console.log("video")
         var el = document.createElement('video');
             el.src = 'filename';
         // make your own video player !!!
      } else {
         console.log("image")
         var el = document.createElement("IMG");
             el.setAttribute("src", filename);
             document.getElementById("res").appendChild(x);
      }
      document.getElementById("dynamic_file_load").appendChild(el);
  }
  checkeExtension("<%= @post.file.url %>");
</script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章