Home » Javascript » Blueimp validate image dimensions before uploading

Blueimp validate image dimensions before uploading

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’m using the Blueimp uploader (https://github.com/blueimp/jQuery-File-Upload/) to upload some photos. And it must only upload images not bigger than 800×600 pixels. I tried all other similar workarounds found in Stack Overflow but none of them stops the uploading other than displaying the error message.
blueimp fileupload – check the image width and height before upload

I need to stop the uploading if any image exceeds the above dimensions.

Here’s my source:

$(function () {
    'use strict';

    $('#fileupload').fileupload({
        add: function (e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(gif|jpe?g|png|tiff?)$/i;

            var reader = new FileReader();
            reader.readAsDataURL(data.files[0]);
            reader.data = data;
            reader.file = data.files[0];
            reader.onload = function (_file, uploadErrors) {
                console.log(this.data);
                var image = new Image();
                image.src = _file.target.result;
                image.file = this.file;
                image.data = this.data;
                image.onload = function () {
                    console.log(this.data);
                    var w = this.width,
                            h = this.height,
                            n = this.file.name;
                    if ((w > 800 && h > 600) || (w > 600 && h > 800)) {
                        reader.data.files.pop();
                        alert('Image is too big');
                    }
                };
                image.onerror = function () {
                    alert("Please select a valid image file (jpg and png are allowed)");
                };
            };

            //validation file types
            if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }

            //validation max file size
            if (data.originalFiles[0]['size'] > 15000000) {
                uploadErrors.push('Photos may not be larger than 15MB');
            }
            if (uploadErrors.length > 0) {
                $('#msgBox').html(uploadErrors.join("<br />"));
            } else {
                data.submit();
            }
        },
        url: 'server/php/',
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $("#imagelist").append("<p>"+ file.name +"</p>");
            });
        },
    }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Answers: