Rails file_field大小限制

我目前有上面的图片上传,但我还想添加一个限制,阻止用户上传任何height低于50px文件。 这可能吗?

 file_field "form", "image", accept: 'image/png,image/gif,image/jpeg' 

试试这个,也许这会对你有所帮助: 参考

 validate :validate_image_size def validate_image_size image = MiniMagick::Image.open(picture.path) unless image[:height] < 50 errors.add :image, "should be 50px minimum!" end end 

如果您使用MiniMagick这将适用于您。

这可能吗?

是的,这是可能的,但你需要一些JavaScript在客户端这样做,这是一个例子。 将html输入更改为rails helper。

HTML

  /* */ This image is going to load 

js代码:

 // The upload listner function $('https://stackoverflow.com/questions/44267861/rails-file-field-size-restrictions/#image').on('change', function() { var img = document.getElementById('image_on_load'); var reader = new FileReader(); // add uploaded image to the img element reader.onloadend = function() { $('https://stackoverflow.com/questions/44267861/rails-file-field-size-restrictions/#image_on_load').prop('src', reader.result) } reader.readAsDataURL(this.files[0]); // listen onload event and get dimension img.onload = function(image) { $('https://stackoverflow.com/questions/44267861/rails-file-field-size-restrictions/#image_info_width').text('Width: ' + image.target.width) $('https://stackoverflow.com/questions/44267861/rails-file-field-size-restrictions/#image_info_heigth').text('Height: ' + image.target.height) // here you able to upload or reject // file accourding to dimension } }); 

在此示例中,图像已上传,您可以获得宽度和高度。

JSFIDDLE

阅读Rails 7 Must-Reads about JavaScript with Ruby on Rails JS如何7 Must-Reads about JavaScript with Ruby on Rails