1

The website that I'm working on has an option to upload images, but I must validate the image's dimensions (width, height) before uploading to the server side or before submitting.

For example the image must be 250x250, otherwise an alert occurs and the user can't upload the image, here's a part of my code:

<form action="upload_file.php" method="post"  enctype="multipart/form-data" name = "upload" id="insertBook" onSubmit="return validateImage();"> 
    <input type="file" name="image" value="upload" id = "myImg">
    <input type="submit" name = "submit">           
</form>

validateImage function now just checks for the extensions, I want it also to check for the dimensions.

Here's the code so far:

function validateImage(){
    var allowedExtension = ["jpg","jpeg","gif","png","bmp"];
    var fileExtension = document.getElementById('myImg').value.split('.').pop().toLowerCase();
    var isValidFile = false;
    for(var index in allowedExtension) {
        if(fileExtension === allowedExtension[index]) {
            isValidFile = true; 
            break;
        }
    }
    if(!isValidFile) {
        alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
    }
    return isValidFile;
}

Thank you! :)

  • 1
    I'd personnaly not use a client-side validation for this kind of stuff. A server-side would ensure that the user doesn't alter the function or bypass it before sending the image. Plus depending on your backend, the image handling might have some function to check the size. Working on an in-memory file (in ram) would be the most efficient way to achieve this. Just write the image to the disk if it validates, or drop it if it didn't. Of course you can check for the size before the upload. Be it's unsafe. Check for it on the server-side. – Depado Jun 19 '14 at 10:05
  • 1
    @Depado client side validation is for user comfort and I prefer client side verification and error reporting. I believe on server side You should just validate and drop the request if invalid and leave all the nasty UI stuff of displaying error messages for client side. – Iman Mohamadi Feb 08 '15 at 05:30
  • 1
    @ImanMohamadi You're right on this point. Though client-side validation is only for the UI stuff. You should never rely on the client-side for this kind of things, that's why I say it's unsafe. Always do the server-side validation first, then the client-side. Otherwise you may think the process on the client-side is safe. Client-side validation is always optionnal. Sure it may save a few bad requests to the server, but if someone really wants to upload an image, he could just bypass it. – Depado Feb 10 '15 at 09:05

2 Answers2

3
function validateImage(){
    var isValidFile = false;
    var image = document.getElementById('myImg');

    var allowedExtension = ["jpg","jpeg","gif","png","bmp"];

    var srcChunks = image.src.split( '.' );
    var fileExtension = srcChunks[ srcChunks.length - 1 ].toLowerCase();

    if ( image.width !== image.height !== 250 ) {
        console.log( 'Size check failed' );
        return false;
    } 

    for(var index in allowedExtension) {
        if(fileExtension === allowedExtension[index]) {
            isValidFile = true; 
            break;
        }
    }

    if(!isValidFile) {
        alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
    }

    return isValidFile;
}
Ingmars
  • 998
  • 5
  • 10
  • IT WORKED! Thanks! May I ask what those lines do? "var srcChunks = image.src.split( '.' ); var fileExtension = srcChunks[ srcChunks.length - 1 ].toLowerCase();" @Ingmars – Osama Daraghme Jun 19 '14 at 10:30
  • 2
    He is splitting the filename using the "." as separator and takes the last one, so it's the actual extension. For exemple you have a file named 'hello.world.jpg'. His code will only take 'jpg'. By the way that for loop to check the existence of the extension should now be replaced by the indexOf method. – Depado Jun 19 '14 at 12:43
1

Related to this topic

As I said in my comment, you can check for the size on the client-side but it's unsafe as the javascript may be bypassed, and your validation would serve no purpose. If someone really wants to upload a file that is 5Go, he just have to redefine your check function.

A server side validation isn't accessible by the client. Moreover depending on your backend and your image handling (Are you handling it like a simple file ? Or do you have some lib to work with images ?), you may find some methods to help you with image dimensions. For example in python I use PIL (Pillow for 3.x version) to check for image information, size, dimension, content, check if it's a real file or not... Actually it's really easy to upload a corrupted file that contains some php code in it (for example) so you should be really careful when you let users upload content to your server.

Community
  • 1
  • 1
Depado
  • 4,811
  • 3
  • 41
  • 63
  • Thank you for your answer. But the problem with most answers is that they use jQuery and I can't yet, and sadly I have no time to learn it. :( – Osama Daraghme Jun 19 '14 at 10:11
  • 1
    Please check the related topic. He is not using JQuery to get the image information. He is using it to modify the DOM. You don't need JQuery to get those information on modern browsers. If you're affraid of compatibility with older browser, juste validate server-side. – Depado Jun 19 '14 at 10:16