【发布时间】:2017-10-31 06:14:59
【问题描述】:
我目前有以下用于上传图像,但我还想添加一个限制,以防止用户在height 中上传小于50px 的任何文件。这可能吗?
file_field "form", "image", accept: 'image/png,image/gif,image/jpeg'
【问题讨论】:
标签: javascript ruby-on-rails file input upload
我目前有以下用于上传图像,但我还想添加一个限制,以防止用户在height 中上传小于50px 的任何文件。这可能吗?
file_field "form", "image", accept: 'image/png,image/gif,image/jpeg'
【问题讨论】:
标签: javascript ruby-on-rails file input upload
试试这个,也许对你有帮助:Reference
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 助手。
html
<input id="image" name="img" type="file" />
/* */
<img src="#" alt="This image is going to load" id="image_on_load" />
<p id='image_info_width'> </p>
<p id='image_info_heigth'> </p>
js代码:
// The upload listner function
$('#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() {
$('#image_on_load').prop('src', reader.result)
}
reader.readAsDataURL(this.files[0]);
// listen onload event and get dimension
img.onload = function(image) {
$('#image_info_width').text('Width: ' + image.target.width)
$('#image_info_heigth').text('Height: ' + image.target.height)
// here you able to upload or reject
// file accourding to dimension
}
});
在此示例中,图片已上传,您可以获取宽度和高度。
阅读如何在 Rails 中使用 JS
7 Must-Reads about JavaScript with Ruby on Rails
【讨论】: