Rails File_field Size Restrictions
I currently have the below for uploading images, but I also want to add a restriction that prevents users from uploading any file less than 50px in height. Is this possible? file_f
Solution 1:
Try this one, Maybe this will help you: Reference
validate :validate_image_sizedefvalidate_image_size
image = MiniMagick::Image.open(picture.path)
unless image[:height] < 50
errors.add :image, "should be 50px minimum!"endend
This will work for you if you use MiniMagick
.
Solution 2:
Is this possible?
Yes it's possible, but you need some javascript to do it on the client side, here is am example. Change that html input to the rails helper.
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>
the js code:
// The upload listner function
$('#image').on('change', function() {
var img = document.getElementById('image_on_load');
var reader = newFileReader();
// 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
}
});
In this example image was uploaded and the you able to get the width and the height.
Read how the works with JS in Rails
7 Must-Reads about JavaScript with Ruby on Rails
Post a Comment for "Rails File_field Size Restrictions"