2011-03-11 142 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; 
    } 
}