3 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以在提交表單之前檢查它們:
window.URL = window.URL || window.webkitURL;
$("form").submit( function( e ) {
var form = this;
e.preventDefault(); //Stop the submit for now
//Replace with your selector to find the file input in your form
var fileInput = $(this).find("input[type=file]")[0],
file = fileInput.files && fileInput.files[0];
if( file ) {
var img = new Image();
img.src = window.URL.createObjectURL( file );
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
if( width == 400 && height == 300 ) {
form.submit();
}
else {
//fail
}
};
}
else { //No file was input or browser doesn't support client side reading
form.submit();
}
});
這僅適用于現(xiàn)代瀏覽器,因此您仍然必須在服務(wù)器端檢查尺寸。您也不能信任客戶端,因此這是您仍然必須在服務(wù)器端檢查它們的另一個(gè)原因。

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
可能會晚一點(diǎn),但這是使用promise接受的答案的現(xiàn)代ES6版本
const getUploadedFileDimensions: file => new Promise((resolve, reject) => {
try {
let img = new Image()
img.onload = () => {
const width = img.naturalWidth,
height = img.naturalHeight
window.URL.revokeObjectURL(img.src)
return resolve({width, height})
}
img.src = window.URL.createObjectURL(file)
} catch (exception) {
return reject(exception)
}
})
你會這樣稱呼它
getUploadedFileDimensions(file).then(({width, height}) => {
console.log(width, height)
})
添加回答
舉報(bào)