Canceling File Uploads Using The ASP.NET FileUpload Control

The ASP FileUpload control can be handy if you are working with Web Forms as a means to easily integrate file uploading into your application and aren't experienced enough to work directly with HTML file inputs, Flash or jQuery based alternatives.

The Problem

Meet our friend the FileUpload Control:

  1. <!-- File Uploader -->   
  2. <asp:FileUpload ID="files" name="files[]" runat="server" multiple="multiple" />   
A very common use-case for the FileUpload control may be a simple application that allows a user to upload images or some other types of files and be able to see a thumbnail of the image after it has been uploaded, but has not yet been submitted or posted to the server.

File upload

Which can be created using the following code:
  1. <!-- The necessary scripts that do work son. -->   
  2. < script type = 'text/javascript' > function handleFileSelect(evt)  
  3. {  
  4.     // FileList object  
  5.     var files = evt.target.files;  
  6.     // Loop through the FileList and render image files as thumbnails.  
  7.     for (var i = 0, f; f = files[i]; i++)  
  8.     {  
  9.         // Only process image files.  
  10.         if (!f.type.match('image.*'))  
  11.         {  
  12.             continue;  
  13.         }  
  14.         var reader = new FileReader();  
  15.         // Closure to capture the file information.  
  16.         reader.onload = (function (theFile)  
  17.         {  
  18.             return function (e)  
  19.             {  
  20.                 // Render thumbnail.  
  21.                 var span = document.createElement('span');  
  22.                 // Creates a thumbnail with an onclick function  
  23.                 // that will handle the mock deletion  
  24.                 span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '" onclick="deleteImage(this);"/>'].join('2015-02-03 05:12:55');  
  25.                 document.getElementById('list').insertBefore(span, null);  
  26.             };  
  27.         })(f);  
  28.         // Read in the image file as a data URL.  
  29.         reader.readAsDataURL(f);  
  30.     }  
  31. } < /script>  
However, if you decided that you no longer wanted one of the images and wired up a simple delete mechanism to remove the thumbnail of that file through Javascript; they could easily remove the thumbnail but wouldn't the file itself still be posted to the server to be uploaded?

 

  1. // The image was clicked delete it  
  2. function deleteImage(imgToDelete) {   
  3.    imgToDelete.style.display = "none";  
  4. }  
Since the FilesList collection (that stores all of the Files within the FileUpload) is read-only there really isn't any way to remove or modify a single file from the collection without getting rid of them all by simply wiping the value property:
  1. // Hasta La Vista Files!  
  2. document.getElementById('yourFileUpload').value = "";   
The Workaround

So how could you handle removing images that are already present within your Request.files collection, just waiting to be uploaded? Well, here is a simple workaround to handle that.

Place a hidden field within your <form> element that houses your FileUpload control to store all of the files that are marked for deletion:
  1. <asp:HiddenField ID="filesToIgnore" runat="server" />   
Within your JavaScript delete function, which removes your thumbnail image, add the following code:
  1. function delClick(imgToDelete)  
  2. {  
  3.     // Add this line (your thumbnail will need to reference   
  4.     // a file name or property from your actual file – this  
  5.     // example stores the FileName in the title property  
  6.     document.getElementById('filesToIgnore').value += (imgToDelete.title + ",");  
  7.     // Additional code here to remove the thumbnail  
  8.     imgToDelete.style.display = “none”;  
  9. }  
This will now create a comma-delimited list that you can use to store all of the values of the files that you want to ensure are not uploaded.

When your form is posted, you will need to create a collection based on your hidden filesToIgnorefield within your Page Load or related event:
  1. // Upload click event  
  2. protected void btnUpload_Click(object sender, EventArgs e)  
  3. {  
  4.     // Get files to be ignored (not uploaded)  
  5.     string[] ignoredFiles = filesToIgnore.Value.Split(new char[]  
  6.     {  
  7.         ','  
  8.     }, StringSplitOptions.RemoveEmptyEntries);  
  9.     // Iterate through posted files  
  10.     HttpFileCollection uploadFiles = Request.Files;  
  11.     for (int i = 0; i < uploadFiles.Count; i++)  
  12.     {  
  13.         HttpPostedFile postedFile = uploadFiles[i];  
  14.         // If it isn't a file meant for deletion - don't upload  
  15.         if (!ignoredFiles.Any(c => postedFile.FileName.Contains(c)))  
  16.         {  
  17.             // Upload your file here  
  18.             Response.Write(String.Format("{0} Uploaded!<br />", postedFile.FileName));  
  19.         }  
  20.     }  
  21. }  
Other Considerations

Although this example was a very hasty one, there are many methods of handling this. You may want to seriously consider using one of the many jQuery based plug-ins that supports multiple file uploads or creating your own solution that uses a single file upload element for each file, which would allow you to manage them independently.

Flash plugins can often be great at handling File Upload operations as well; although many people including myself cringe that the sight of that five-letter F-word. 


Similar Articles