In the client to upload files, usually need to limit the size and format of the file, the most common practice is to use a plug-in, some mature plug-in is really good interface, and powerful, but the drawback is: sometimes encounter browser compatibility issues. This article will write a "pristine" jquery plugin, so that it can limit the size and format of uploaded files.
First, write a plug-in called Checkfiletypeandsize.js. Limit the file format by judging whether the suffix name of the current file is included in the pre-set suffix an array group, to limit the file size by judging whether the size of the current file under IE and other browsers is larger than the maximum file size allowed by the preset, and to provide a format error, A callback function that exceeds the limit size and meets the criteria.
(function ($) {
$.fn.checkfiletypeandsize = function (options) {
Default settings
var defaults = {
Allowedextensions: [],
Unit is KB, default maximum file size 1mb=1024kb
Success:function () {},
Extensionerror:function () {},
Sizeerror:function () {}
};
Merge settings
options = $.extend (defaults, options);
Traversing elements
return the. each (function () {
$ (this). On (' Change ', function () {
Get file path
var FilePath = $ (this). Val ();
File path for lowercase letters
var Filelowerpath = Filepath.tolowercase ();
Gets the suffix name of the file
var extension = filelowerpath.substring (Filelowerpath.lastindexof ('. ') + 1);
Determine if the suffix name is included in the pre-set, allowed suffix an array group
if ($.inarray (extension, options.allowedextensions) = =-1) {
Options.extensionerror ();
$ (this). focus ();
Else {
Try {
var size = 0;
if ($.browser.msie) {//ie Legacy browser
New ActiveXObject ("scripting.filesystemobject");
var fileobj = Filemgr.getfile (FilePath);
Byte
size = size/1024; //kb
Size = SIZE/1024;//MB
Else {//other browsers
Size = $ (this) [0].files[0].size; //byte
size = size/1024; //kb
Size = SIZE/1024;//MB
}
if (Size > Options.maxsize) {
Options.sizeerror ();
Else {
Options.success ();
}
Catch (e) {
Alert (" error:" + e);
}
}
});
});
};
}) (JQuery);
The call on the client becomes very simple.
<input type= "file" name= "F" id= "f"/>
@section scripts
{
<script src= "~/scripts/checkfiletypeandsize.js" ></script>
<script type= "text/javascript" >
$ (function () {
$ (' #f '). Checkfiletypeandsize ({
Allowedextensions: [' jpg '],
Maxsize:10,
Success:function () {
Alert (' OK ');
},
Extensionerror:function () {
Alert (' Allowed format: jpg ');
return;
},
Sizeerror:function () {
Alert (' Maximum size 10kb ');
return;
}
});
});
</script>
}
Write a jquery plugin that limits the size and format of uploaded files