


Client js determines the file type and file size and limits the upload size_javascript skills
May 16, 2016 pm 05:13 PMDue to project needs! A script is needed to determine the size and file type on the client side! It’s so hard to find information online! I simply wrote an example myself and tested the file upload size limit. It is compatible with ie6, ie7, ie8, Google Chrome, ff and other browsers
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target,id) {
var fileSize = 0;
var filetypes =[".jpg",".png",".rar",".txt",".zip",". doc",".ppt",".xls",".pdf",".docx",".xlsx"];
var filepath = target.value;
var filemaxsize = 1024*2;/ /2M
if(filepath){
var isnext = false;
var fileend = filepath.substring(filepath.indexOf("."));
if(filetypes && filetypes.length>0 ){
for(var i =0; i<filetypes.length;i ){
if(filetypes[i]==fileend){
isnext = true;
break;
}
}
}
if(!isnext){
alert("This file type is not accepted!");
target.value ="";
return false;
}
}else{
return false;
}
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject ("Scripting.FileSystemObject");
if(!fileSystem.FileExists(filePath)){
alert("The attachment does not exist, please re-enter! ");
return false;
}
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[ 0].size;
}
var size = fileSize / 1024;
if(size>filemaxsize){
alert("Attachment size cannot be larger than" filemaxsize/1024 "M!" );
target.value ="";
return false;
}
if(size<=0){
alert("The attachment size cannot be 0M!");
target.value ="";
return false;
}
}
</script>
</head>
<body>
< input type="file" name="contractFileName" style="width: 500px;" onchange="fileChange(this);"/>
</body>
</html>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What file type is et 'Must read: How to open et files'

How to fix remote procedure call failed error in Windows 11

Use java's File.isDirectory() function to determine whether the file exists and is a directory type

Java program to get the size of a given file in bytes, kilobytes and megabytes

Get file size using filesize() function in PHP
![How to Search in Windows 11 [4 Ways to Explain]](https://img.php.cn/upload/article/000/465/014/168138726979003.png?x-oss-process=image/resize,m_fill,h_207,w_330)
How to Search in Windows 11 [4 Ways to Explain]
