繁体   English   中英

上传前检查图片大小

[英]checking image size before upload

我注意到在将个人资料图片上传到 Twitter 时,会在上传前检查其大小。 谁能指出我这样的解决方案?

谢谢

我已经在 chrome 中测试了这段代码,它工作正常。

var x = document.getElementById('APP_LOGO'); // get the file input element in your form
var f = x.files.item(0); // get only the first file from the list of files
var filesize = f.size;
alert("the size of the image is : "+filesize+" bytes");

var i = new Image();
var reader = new FileReader();
reader.readAsDataURL(f);
i.src=reader.result;
var imageWidth = i.width;
var imageHeight = i.height;
alert("the width of the image is : "+imageWidth);
alert("the height of the image is : "+imageHeight);

如果您正在检查文件大小,您可以在上传前使用诸如uploadify 之类的东西来检查文件大小。

检查实际文件尺寸(高度/宽度)可能需要在服务器上完成。

我认为除非您使用闪光灯,否则这是不可能的。 您可以使用uploadifyswfupload进行此类操作。

像这样的东西应该处理异步加载的表单,有或没有“多个”设置的输入,并避免使用 FileReader.readAsDataURL 和 Image.src 时发生的竞争条件。

$('#formContainer').on('change', '#inputFileUpload', function(event) {
  var file, _fn, _i, _len, _ref;
  _ref = event.target.files;
  _fn = function(file) {
    var reader = new FileReader();
    reader.onload = (function(f) {
      return function() {
        var i = new Image();
        i.onload = (function(e) {
          var height, width;
          width = e.target.width;
          height = e.target.height;
          return doSomethingWith(width, height);
        });
        return i.src = reader.result;
      };
    })(file);
    return reader.readAsDataURL(file);
  };
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    file = _ref[_i];
    _fn(file);
  }
});

注意:需要 jQuery、HTML5、挂钩到如下结构:

<div id="formContainer">
  <form ...>
  ...
    <input type="file" id="inputFileUpload"></input>
  ...
  </form>
</div>

加载图像时需要检查图像宽度和高度。

var img = new Image;
img.src = URL.createObjectURL(file);
img.onload = function() {
    var picWidth = this.width;
    var picHeight = this.height;

    if (Number(picWidth) > maxwidth || Number(picHeight) > maxheight) {
        alert("Maximum dimension of the image to be 1024px by 768px");
        return false;
    }
}

这对我来说非常有效

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {
var file, img;


if ((file = this.files[0])) {
    img = new Image();
    img.onload = function() {
        if((this.width < 800)||(this.height < 400)){
            alert('Image too small. Images must be bigger than 800 x 400');
            $('#file').val('');
        }

    };
    img.onerror = function() {
        alert( "not a valid file: " + file.type);
    };
    img.src = _URL.createObjectURL(file);

}

});

感谢原作者: http : //jsfiddle.net/4N6D9/1/

我修改了它以指定上传的最小宽度和高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM