Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset fileupload control from javascript

I have a ASP website page where i have a upload control added

<asp:FileUpload ID="FileUpload1" runat="server" 
                        BorderStyle="None" Width="215px" onchange="return checkfile();" style="margin-left: 14px" BackColor="#F0F0F0" />

From javascript i am validating the file which will be uploaded. If it is of type .exe then I will not allow to upload and give a message. if not i will display the file name in label "lblFileName" . But the problem if error(in case file is exe) then i want to reset the upload control(FileUpload1) . Now it will show only message but allows form to submit along with the .exe file.So how I can reset it?

 function checkfile() {

     var filename = document.getElementById("FileUpload1").value;
     var lastIndex = filename.lastIndexOf("\\");


     if (lastIndex >= 0) {
         filename = filename.substring(lastIndex + 1);
     }

    var FileExt = filename.split('.').pop();

    if (FileExt == "exe") {  

        document.getElementById('<%=lblFileName.ClientID%>').innerHTML = "you cannot attach exe file";
    return false;

     }
    else {
        document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
    }
  }

enter image description here

like image 453
IT researcher Avatar asked Dec 28 '25 19:12

IT researcher


1 Answers

Your code is the problem onchange="return checkfile();"

And your function should look like

    function checkfile() {

         var filename = document.getElementById("FileUpload1").value;
         var lastIndex = filename.lastIndexOf("\\");


         if (lastIndex >= 0) {
             filename = filename.substring(lastIndex + 1);
         }

        var FileExt = filename.split('.').pop();

        if (FileExt == "exe") {         
            document.getElementById('lblFileName').innerHTML = "you cannot attach exe file";
            document.getElementById("FileUpload1").value='';
            return false;

         }
         else {
            document.getElementById('lblFileName').innerHTML = filename;
        }
      }

Return will disallow file to put in your file upload control so this will solve your problem

Please check demo here

like image 78
Just code Avatar answered Dec 31 '25 07:12

Just code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!