HTML文件输入接受具有特定维度的图像

时间:2017-02-21 23:36:43

标签: javascript html

我知道这可能需要一些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">

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

2 个答案:

答案 0 :(得分:2)

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

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

};

答案 1 :(得分:0)

由于您在那里有文件,因此首先需要将其加载到图像中。之后,您可以检查高度和宽度,看它是否符合您的需求。请注意,服务器端验证也是必要的,因为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