You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在视图中显示文件大小?[Rails - Shrine Gem]

在Shrine Gem中显示文件大小的方法

嘿,我来帮你搞定用Shrine Gem在视图里显示文件大小的问题~其实很简单,结合Shrine自带的属性和一个小辅助方法就能实现:

1. 先搞懂Shrine上传对象的属性

每个通过Shrine上传的文件(比如你的Project#cover_image或者Photo#image),都自带一个size方法,它会返回文件的字节数(比如1024就代表1KB)。不过直接显示字节数对用户不太友好,所以我们需要做个格式化处理。

2. 写一个文件大小格式化的辅助方法

在app/helpers/application_helper.rb里添加这个方法,它能把字节数转换成人类易读的格式(比如KB、MB):

def format_file_size(bytes)
  return "0 Bytes" if bytes == 0
  units = %w[Bytes KB MB GB TB]
  exponent = (Math.log(bytes) / Math.log(1024)).floor
  exponent = units.size - 1 if exponent >= units.size
  "#{(bytes / 1024**exponent).round(2)} #{units[exponent]}"
end

3. 在视图里调用这个方法显示大小

结合你的模型关联关系,在Project的show视图里可以这么用:

显示Project的封面图大小

<% if @project.cover_image.attached? %>
  <p>封面图大小: <%= format_file_size(@project.cover_image.size) %></p>
<% end %>

遍历Album和Photo显示每个图片的大小

<% @project.albums.each do |album| %>
  <h3><%= album.name %></h3>
  <% album.photos.each do |photo| %>
    <% if photo.image.attached? %>
      <div>
        <p>文件名: <%= photo.image.original_filename %></p>
        <p>文件大小: <%= format_file_size(photo.image.size) %></p>
      </div>
    <% end %>
  <% end %>
<% end %>

小提示

  • 一定要用attached?判断文件是否已经上传,避免因为空对象调用size方法报错。
  • 如果不需要格式化,直接显示字节数的话,直接写<%= @project.cover_image.size %>就可以啦。

内容的提问来源于stack exchange,提问作者Aipack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:20:43