Validate Image Size before upload using JavaScript

In this article, we will learn how to validate image size on button click using JavaScript. In this, we have a file uploader (to upload the image) , span(for showing error messages) and button. On buttonclick we validate the size of image.

 




Image compression without losing quality in asp.netc#, How to convert div into an image using JQuery ,

 

Source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

 

        <fieldset style="width: 350px">

            <legend>Validate Image Size before upload using JavaScript</legend>

            <input type="file" id="fileuploader" />

            <br />

            <span id="sapamessage" style="color: red;"></span>

            <br />

            <br />

 

            <input type="button" value="Upload" onclick="return Validate()" />

        </fieldset>

 

        <script type="text/javascript">

            function Validate() {

                var file = document.getElementById("fileuploader");

                var msg = document.getElementById("sapamessage");

                msg.innerHTML = "";

                var size = parseFloat(file.files[0].size);

                var maxSizeKB = 40; //Size in KB.

                var maxSize = maxSizeKB * 1024; //File size is returned in Bytes.

                if (size > maxSize) {

                    msg.innerText = "Max file size " + maxSizeKB + "KB allowed.";

                    file.value = "";

                    return false;

                }

            }

        </script>

 

    </form>

</body>

</html>

 

Out-Put:-


Validate Image Size before upload using JavaScript  Validate Image Size before upload using JavaScript Reviewed by NEERAJ SRIVASTAVA on 12:51:00 PM Rating: 5

No comments:

Powered by Blogger.