使用 Carrierwave 验证上传大小

发布于 2024-10-12 23:17:16 字数 265 浏览 2 评论 0原文

在我们最新的应用程序中,我们需要处理一些上传,我之前使用过回形针,一切正常!但我们正在尝试 Carrierwave,它看起来很有希望,但是,我找不到如何验证附件文档似乎没有任何相关信息,我们是否应该手动将其添加到通过自定义验证器的模型?

提前致谢!

In our latest application we need to process some uploads, I've worked with paperclip before and everything just works! but we're giving carrierwave a try, it looks promising but, I can't find how to validate the size of an attachment, it seems like the documentation doesn't have any information about it, should we add it manually to the model via a custom validator?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独行侠 2024-10-19 23:17:16

我制作了一个活动模型 文件验证器 gem,用于检查 Carrierwave、PaperClip 的内容类型和文件大小验证, Drangonfly、Refile(希望它能与其他上传解决方案配合使用)。它根据文件的内容检测内容类型,并且具有媒体类型欺骗检测器。它在上传之前和之后都有效。

I've made an Active Model File Validators gem that checks content type and file size validation for Carrierwave, PaperClip, Drangonfly, Refile (hopefully it will work with other uploading solutions). It detects the content type based on the content of the file and it has a media type spoof detector. It works both before and after uploads.

你列表最软的妹 2024-10-19 23:17:16

1.0 版本开始,CarrierWave 具有内置文件大小验证功能。

安装最新的rierwave gem

gem 'carrierwave', '~> 1.0'

添加方法size_range以提供最小大小和最大大小

class ImageUploader < CarrierWave::Uploader::Base
  def size_range
    0..2.megabytes
  end

在模型中添加validates_integrity_of以验证文件大小(和内容类型) )的图像。

class Image < ApplicationRecord
  mount_uploader :image, ImageUploader

  validates_integrity_of :image

Since 1.0 version CarrierWave has built-in file size validation.

Install latest carrierwave gem

gem 'carrierwave', '~> 1.0'

Add method size_range to provide a min size and a max size

class ImageUploader < CarrierWave::Uploader::Base
  def size_range
    0..2.megabytes
  end

In model add validates_integrity_of to valid a file size (and content type) of an image.

class Image < ApplicationRecord
  mount_uploader :image, ImageUploader

  validates_integrity_of :image
许一世地老天荒 2024-10-19 23:17:16

这是我想出的解决方案 - 诀窍是我无法检查文件直接调整大小,因为如果文件未上传,则会产生 Fog RubyGem 炸弹。我希望有一种更简洁的方式来询问 CarrierWave 文件是否已上传。

Here is the solution that I came up with - the trick was that I couldn't check the file size directly as that made the Fog RubyGem bomb if the file hadn't been uploaded. I would expect there to be a cleaner way to ask CarrierWave if a file was uploaded.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文