Write a jQuery plug-in that limits the size and format of the uploaded file to upload the file jquery
When uploading files on a client, you usually need to restrict the file size and format. The most common method is to use a plug-in. Some mature plug-ins do have a nice UI and are powerful, but the disadvantage is that sometimes browser compatibility problems occur. In this article, we will write a jQuery plug-in "Original Ecology" to limit the size and format of uploaded files.
First, write a plug-in named checkFileTypeAndSize. js. The file format is restricted by determining whether the suffix of the current file is included in the preconfigured allowed suffix array; determine whether the size of the current file in IE and other browsers is greater than the maximum size allowed by the preset settings to limit the file size; it also provides callback functions that are incorrectly formatted, exceed the limit, and meet the conditions.
(function ($) {
$.fn.checkFileTypeAndSize = function (options) {
// Default settings
var defaults = {
allowedExtensions: [],
MaxSize: 1024, // The unit is KB. The default maximum file size is 1 MB = 1024KB.
success: function () { },
extensionerror: function () { },
sizeerror: function () { }
};
// Merge settings
options = $.extend(defaults, options);
// Traverse Elements
return this.each(function () {
$(this).on('change', function () {
// Obtain the file path
var filePath = $(this).val();
// File path with lower-case letters
var fileLowerPath = filePath.toLowerCase();
// Get the file suffix
var extension = fileLowerPath.substring(fileLowerPath.lastIndexOf('.') + 1);
// Determine whether the suffix is included in the preset and allowed suffix Array
if ($.inArray(extension, options.allowedExtensions) == -1) {
options.extensionerror();
$(this).focus();
} else {
try {
var size = 0;
If ($. browser. msie) {// ie old browser
var fileMgr = new ActiveXObject("Scripting.FileSystemObject");
var fileObj = fileMgr.getFile(filePath);
size = fileObj.size; //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>
}