Write a jQuery plug-in that limits the size and format of the uploaded file to upload the file jquery

Source: Internet
Author: User

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>
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.