ASP.NET中自带的上传控件如果文件很大的话通常会死机,如果能在客户端验证的话,就很好了。于是从网上东拼西凑个点JS。


//
验证浏览器
// 添加人:冯俊杰
// 添加日期:2010-03-30
var Sys = {};
if (navigator.userAgent.indexOf( " MSIE " ) > 0 ) {
Sys.ie = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " Firefox " ) > 0 ){
Sys.firefox = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " 'Chrome " ) > 0 ){
Sys.firefox = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " 'Opera " ) > 0 ){
Sys.firefox = true ;
}
// 清空上传文件大小超过5M给提示不让上传
// 添加人:冯俊杰
// 添加日期:2010-03-30
function checkFileChange(obj) {
var filesize = 0 ;
if (Sys.firefox){
filesize = obj.files[ 0 ].fileSize;
} else if (Sys.ie){
var filePath = obj.value;
var image = new Image();
image.dynsrc = filePath;
filesize = image.fileSize;
}
if (filesize > 5 * 1024 * 1024 ) // 大于5M
{
window.alert( ' More than 5M,Please Try again! ' );
clearFileInput(obj);
return false ;
}
}
// 清空验证后的fileupload控件内容
// 添加人:冯俊杰
// 添加日期:2010-03-30
function clearFileInput(file){
var form = document.createElement( ' form ' );
document.body.appendChild(form);
var pos = file.nextSibling;
form.appendChild(file);
form.reset();
pos.parentNode.insertBefore(file,pos);
document.body.removeChild(form);
}
// 添加人:冯俊杰
// 添加日期:2010-03-30
var Sys = {};
if (navigator.userAgent.indexOf( " MSIE " ) > 0 ) {
Sys.ie = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " Firefox " ) > 0 ){
Sys.firefox = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " 'Chrome " ) > 0 ){
Sys.firefox = true ;
}
if (isFirefox = navigator.userAgent.indexOf( " 'Opera " ) > 0 ){
Sys.firefox = true ;
}
// 清空上传文件大小超过5M给提示不让上传
// 添加人:冯俊杰
// 添加日期:2010-03-30
function checkFileChange(obj) {
var filesize = 0 ;
if (Sys.firefox){
filesize = obj.files[ 0 ].fileSize;
} else if (Sys.ie){
var filePath = obj.value;
var image = new Image();
image.dynsrc = filePath;
filesize = image.fileSize;
}
if (filesize > 5 * 1024 * 1024 ) // 大于5M
{
window.alert( ' More than 5M,Please Try again! ' );
clearFileInput(obj);
return false ;
}
}
// 清空验证后的fileupload控件内容
// 添加人:冯俊杰
// 添加日期:2010-03-30
function clearFileInput(file){
var form = document.createElement( ' form ' );
document.body.appendChild(form);
var pos = file.nextSibling;
form.appendChild(file);
form.reset();
pos.parentNode.insertBefore(file,pos);
document.body.removeChild(form);
}
应用:
<
asp:FileUpload
ID
="FileUpload1"
runat
="server"
onchange
="return checkFileChange(this)"
/>