About the input type="file" upload image, how to limit the resolution of the uploaded image

Keywords: Google Firefox IE JQuery

In the project, you need to limit the resolution of uploaded pictures and be compatible with all browsers (IE8 and above, Google, Firefox). After searching and thinking, we finally solve the bug, record it and hope to help others.

HTML code:

<input  type="file" name="upload0" class="content" id="content" onChange="handleConFiles(this.files);">
<img class="conImage" />

CSS Code:

.conImage{
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image); /* This object is only used to get the original size of the picture under IE, and has no other purpose */
    height: 1px;
    visibility:hidden; 
    overflow: hidden; 
}
JS Code:
var width, height;

function handleConFiles(files) {
    if (navigator.userAgent.indexOf("MSIE 8.0") > 0 || navigator.userAgent.indexOf("MSIE 9.0") > 0) {
        var objPreviewSizeFake = $(".conImage").get(0);//Converting jquery objects to DOM objects
        var fileupload = document.getElementById("head");
        var $fileupload = $(fileupload);
        $fileupload.select();
        $fileupload.blur();
        path = document.selection.createRange().text;


        if (/"\w\W"/.test(path)) {
            path = path.slice(1, -1);
        }


        objPreviewSizeFake.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = path;
        width = objPreviewSizeFake.offsetWidth;
        height = objPreviewSizeFake.offsetHeight;
        if (width > 1024 || height > 120) {
            fill = false;
            alert("The size of the uploaded image should be 1024*120 Between");
        }


        document.selection.empty();
    } else {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var reader = new FileReader();
            var ret = [];
            reader.onload = function (theFile) {
                var image = new Image();
                image.onload = function () {
                    width = this.width;
                    height = this.height;
                    if (width > 1024 || width > 120) {
                        fill = false;
                        alert("The size of the head image should be 1024 x120 Between");
                    }
                };
                image.src = theFile.target.result;
            }
            reader.readAsDataURL(file);
        }
    }
}


The js part can add parameters and repackage according to its own needs, or put the resolution judgment in other places and so on.        

Note: FileReader is used to read files and belongs to HTML5. ie9 and below are not supported.

Note: the test is valid

Posted by uatec on Wed, 15 Apr 2020 08:15:56 -0700