【问题标题】:Rails file_field size restrictionsRails file_field 大小限制
【发布时间】: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


    【解决方案1】:

    试试这个,也许对你有帮助: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,这将适用于您。

    【讨论】:

    • 当我尝试访问高度时它会冻结我的终端
    • 我已经给你参考理解了,哥们用它
    • 我看到了参考,但我必须使用 wavecarrier 吗?目前我只是通过参数将它从 file_field 中取出。请参阅stackoverflow.com/questions/44442569/… 以供参考
    • 是的,你必须使用 wavecarrier
    【解决方案2】:

    这可能吗?

    是的,这是可能的,但您需要一些 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
      }
    });
    

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

    JSFIDDLE

    阅读如何在 Rails 中使用 JS 7 Must-Reads about JavaScript with Ruby on Rails

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 2011-01-13
      • 2011-07-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      相关资源
      最近更新 更多