Check image size before uploading

I noticed when uploading a pic profile on Twitter so that its size was checked before uploading. Can someone point me to such a solution?

thank

+3
source share
5 answers

If you are checking the file size, you can use something like uploadify to check the file size before uploading.

You may need to check the actual file sizes (height / width) on the server.

+2
source

I tested this code in chrome and it works great.

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);
+2
source
+1

Something like this should handle forms being loaded asynchronously, inputs with or without a β€œmultiple” set, and avoid race conditions that occur when using FileReader.readAsDataURL and 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);
  }
});

Note. Requires jQuery, HTML5, structure binding like:

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

You need to check the width and height of the image when loading the image.

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;
    }
}
0
source

All Articles