2011-03-11 127 views
3

我注意到上传配置文件图片给Twitter时,在上传前检查其大小。任何人都可以指向我这样的解决方案吗?上传前检查图片大小

感谢

回答

2

如果您正在检查的文件大小,你可以使用类似uploadify上传前检查文件的大小。

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

1

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

2

我已经在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); 
0

像这样的东西应该有或没有“多”异步加载的形式,投入应对设置,避免在比赛条件下使用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> 
0

你需要检查图像的宽度和高度时,图像的onload。

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