如何通过javascript上传图片大小?

时间:2017-03-24 12:28:32

标签: javascript image file-upload filereader

我想通过javascript获取我上传的图片的大小,但我不能

HTML

<form>
  <input type="file" id="img" multiple>
</form>

JS

var imageData = function(files) {

  var imgWidth  = 0,
      imgHeight = 0;

  var reader  = new FileReader();

  reader.addEventListener('load',function(theFile) {

    var img = new Image();
    img.src = theFile.target.result;

    img.addEventListener('load',function(){

      return {
        imgWidth  :this.width,
        imgHeight :this.height  
      };

    });

  });

  reader.readAsDataURL(files);
};

function checkImg() {
  var files = imgs.files;

  for (var i = 0; i < files.length; i++){
    console.log(imageData(files[i]).imgWidth);
  }
}

var imgs = document.getElementById('img');

imgs.addEventListener('change',checkImg);

http://jsbin.com/tuqoguwudo/3/edit?html,js,console,output

1 个答案:

答案 0 :(得分:0)

使用以下代码,它会在文件加载时提醒文件大小

  var imageData = function(files) {

  var imgWidth  = 0,
      imgHeight = 0;

  var reader  = new FileReader();

  reader.addEventListener('load',function(theFile) {

    var img = new Image();
    img.src = theFile.target.result;
    alert(theFile.total);
    img.addEventListener('load',function(){

      return {
        imgWidth  :this.width,
        imgHeight :this.height  
      };

    });

  });

  reader.readAsDataURL(files);
};

function checkImg() {
  var files = imgs.files;

  for (var i = 0; i < files.length; i++){
    console.log(imageData(files[i]).imgWidth);
  }
}

var imgs = document.getElementById('img');

imgs.addEventListener('change',checkImg);

您需要使用文件的.total属性。