【问题标题】:HTML file input accept images with certain dimensionHTML 文件输入接受具有特定尺寸的图像
【发布时间】:2017-07-11 19:49:26
【问题描述】:

我知道这可能需要一些 javascript,但是我如何告诉我的表单中的输入来拒绝尺寸不同于 64 x 64 的图像而不按下提交按钮。

<div class="form-group">
   <label for="plat_img">Icono</label>
   <input type="file" 
          accept="image/*"
          class="form-control" 
          id="plat_img">

应在选择图像后立即进行验证,如果被拒绝,请通过警报通知用户。

【问题讨论】:

标签: javascript html


【解决方案1】:

这应该可以完成工作,您现在也可以添加一个好的错误消息。

var fileInput = document.getElementById("plat_img");
// listening on when someone selects a file
fileInput .onchange = function(e) {
  e.preventDefault();

  // get the file someone selected
  var file = fileInput.files && fileInput.files[0];

  // create an image element with that selected file
  var img = new Image();
  img.src = window.URL.createObjectURL(file);

  // as soon as the image has been loaded
  img.onload = function() {
    var width = img.naturalWidth,
      height = img.naturalHeight;

    // unload it
    window.URL.revokeObjectURL(img.src);

    // check its dimensions
    if (width <= 64 && height <= 64) {
      // it fits 
    } else {
      // it doesn't fit, unset the value 
      // post an error
      fileInput.value = ""
      alert("only 64x64 images")
    }
  };

};

【讨论】:

  • 解释将是一个很好的补充,而不仅仅是转储代码。只是说。
【解决方案2】:

由于您在那里有一个文件,您首先需要将它加载到一个图像中。之后,您可以检查高度和宽度,看看它是否符合您的需要。请注意,服务器端验证也是必要的,因为 JavaScript 可能会被欺骗。浏览器支持也各不相同。

1. Step: Handle `changed`-event
2. Step: Create Image, handle onload
3. Step: Load the file into the Image object

演示:http://codepen.io/NikxDa/pen/apegZa

【讨论】:

  • 因此,无论谁对此投了反对票,至少可以善意地与我分享原因,以便我可以相应地更新帖子。
猜你喜欢
  • 2019-09-06
  • 1970-01-01
  • 2012-07-24
  • 2017-05-21
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
相关资源
最近更新 更多