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



当前我有以下可以上传图像:

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

在我的方法中,我可以使用此

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

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

正确的方法是在客户端进行。您需要一些JavaScript,这是一个示例。

您无法从参数获取图像宽度和Heigth。

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

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

阅读导轨中的JS的工作方式 7 Must-Reads about JavaScript with Ruby on Rails

最新更新