【问题标题】:How do I restrict image upload height & width on Rails file_field helper?如何限制 Rails file_field 助手上的图像上传高度和宽度?
【发布时间】:2017-10-31 07:29:42
【问题描述】:

目前我有以下上传图片:

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

在我的方法中,我可以用这个访问图像

params[:form_x][:image]

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

【问题讨论】:

    标签: ruby-on-rails image file-upload upload height


    【解决方案1】:

    正确的方法是在客户端进行。你需要一些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

    【讨论】:

    • 这只能在客户端吗?没有办法在服务器端检查?
    • 在服务器上执行此操作的唯一方法是使用carrierwave进行一些预处理,但更好的是在客户端限制图像而不上传。
    猜你喜欢
    • 2012-03-11
    • 2020-04-09
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多