ASP.NET File Upload Progress - Knowledge Base

« Back to Knowledge Base list

How to prevent file uploading for some buttons.

Q:

I have a linkbutton to logout, when a file is selected with the .net file upload control and a click on the logout button, the upload is started. How to prevent it?

A:

By default all buttons (that have submit behavior) causes postback on click. If file is selected in any <input type=”file” …/> of the form, this file is uploading to the server. This behavior doesn’t depend on whether the FileUploadProgress control exists in the page.

You can do the following trick: all buttons that should not cause the file uploading, should clear all inputs with type ‘file’.
Put the following code into your page:

<script type="text/JavaScript">
function
clearFileInputs() {

// get all inputs

var inp = document.getElementsByTagName("input");

for (var i = 0; i < inp.length; i++) {

var el = inp[i];

// input with type 'file' only and not empty

if (el.type == "file" && el.value != "") {

// clear it

if (document.all && !window.opera) {

el.parentNode.insertBefore(el.cloneNode(false), el);

el.parentNode.removeChild(el);

}

else {

var new_span = document.createElement("SPAN");

el.parentNode.insertBefore(new_span, el);

new_span.appendChild(el);

new_span.innerHTML = new_span.innerHTML;

new_span.parentNode.insertBefore(new_span.firstChild, new_span);

new_span.parentNode.removeChild(new_span);

}

}

}

return true;

}
</script>

The button that should not cause the files uploading:

<asp:LinkButton runat="server" OnClick="myHandle"
  OnClientClick="return clearFileInputs();" Text="Logout" />