[英]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 之類的東西來檢查文件大小。
檢查實際文件尺寸(高度/寬度)可能需要在服務器上完成。
像這樣的東西應該處理異步加載的表單,有或沒有“多個”設置的輸入,並避免使用 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.