Click here to Skip to main content
16,020,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using file upload for storing image in database. I am using javascript for validation of valid file type and size. when my validation is false it gives alert but not leaving the file path i choose.

JavaScript
function fileCheck(obj) 
        {
            var fileUploadPath = obj.value;
            var fileSize = obj.files[0].size;
            var extension = fileUploadPath.substring(fileUploadPath.lastIndexOf('.') + 1).toLowerCase();
            if (extension == "gif" || extension == "png" || extension == "bmp" || extension == "jpeg" || extension == "jpg") 
            {
                
            }
            else 
            {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP.");
                
            }
            if (fileSize > 1024) 
            {
                alert("Photo size should not exceeds 1 MB");
                return false;
            } 


<asp:FileUpload ID="FileUpload1" runat="server" onchange="fileCheck(this);"/>
Posted
Updated 9-Apr-14 1:04am
v2

There is a simple way to do it, when validation fails and else part is executing...put
obj.value = ""; after the alert part and before return.

else
{
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP.");
obj.value = "";
return false;
}
 
Share this answer
 
See the changes code
C#
function fileCheck(obj)
        {
            var fileUploadPath = obj.value;
            var fileSize = obj.files[0].size;
            var extension = fileUploadPath.substring(fileUploadPath.lastIndexOf('.') + 1).toLowerCase();
            if (extension == "gif" || extension == "png" || extension == "bmp" || extension == "jpeg" || extension == "jpg")
            {

            }
            else
            {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP.");
       Clear();return false;
            }
            if (fileSize > 1024)
            {
                alert("Photo size should not exceeds 1 MB");
          Clear();
                return false;
            }


Declare Clear function
C#
function Clear()
 {
 var clrFile = document.getElementById("FileUpload1");
 clrFile.select();
 var clr=clrFile.createTextRange();
 clr.execCommand('delete');
 clrFile.focus();

 }
 
Share this answer
 
Comments
Raj Negi 19-Apr-14 4:45am    
There is one problem, i am using 5 file uploads and at run time i detect which file upload is taking file path, your clear() function is only for one file upload...can you write one clear function for every file upload. I dont want 5 clear function for each file upload. Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900