如何限制 Rails file_field 助手的图片上传高度和宽度?

How do I restrict image upload height & width on Rails file_field helper?

目前我有以下上传图片:

<%= file_field "form_x", "image", accept: 'image/png,image/gif,image/jpeg' %>

在我的方法中,我可以用这个

访问图像
params[:form_x][:image]

并通过 params[:form_x][:image].size 读取图像来访问图像的 size。但是如何按像素检查图像的高度和宽度呢?我希望能够通过大小以及高度和宽度来限制图像。

正确的方法是在客户端进行。你需要一些 javascript,这里有一个例子。

您无法从参数中获取图像的宽度和高度。

在服务器上执行此操作的唯一方法是使用 carrierwave for example 进行一些预处理,但更好的方法是在客户端限制图像而不上传

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
  }
});

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

JSFIDDLE

阅读 Rails 中的 JS 是如何工作的 7 Must-Reads about JavaScript with Ruby on Rails