Click here to Skip to main content
15,885,082 members
Articles / Web Development / HTML

Canceling File Uploads using the ASP.NET FileUpload Control

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Apr 2013CPOL2 min read 17.1K   5  
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 integrating file uploading into your application (if you are working with WebForms, that is) and aren’t experienced enough (or just don’t want to) work with the Flash or jQuery-based alternatives.

The Problem

Meet our friend, the FileUpload.

XML
<!-- File Uploader -->
<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).

Example Image Uploader

Example Image Uploader with Image Preview

which can be created using the following code:

JavaScript
<!-- The necessary scripts that do work son. -->
<script type='text/javascript'>
   function handleFileSelect(evt) {
         // FileList object
         var files = evt.target.files;
         // Loop through the FileList and render image files as thumbnails.
         for (var i = 0, f; f = files[i]; i++) {
               // Only process image files.
               if (!f.type.match('image.*')) { continue; }
               var reader = new FileReader();
               // Closure to capture the file information.
               reader.onload = (function (theFile) {
                   return function (e) {
                        // Render thumbnail.
                        var span = document.createElement('span');
                        // Creates a thumbnail with an onclick function 
                        // that will handle the mock deletion
                        span.innerHTML = ['<img class="thumb" src="', e.target.result,
                                          '" title="', escape(theFile.name), 
                                          '" onclick="deleteImage(this);"/>'].join('');
                        document.getElementById('list').insertBefore(span, null);
                   };
               })(f);
               // Read in the image file as a data URL.
               reader.readAsDataURL(f);
        }
   }
</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?

JavaScript
//The image was clicked delete it
function deleteImage(imgToDelete) {
      imgToDelete.style.display = "none";
}

Yes. It would.

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.

JavaScript
//Hasta La Vista Files!
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 (this will store all of the files that are marked for deletion).

ASP.NET
<asp:HiddenField ID="filesToIgnore" runat="server" />

Within your JavaScript “delete” function, which removes your thumbnail image, add the following code:

JavaScript
function delClick(imgToDelete) {
      //Add this line (your thumbnail will need to reference a file name or 
      //property from your actual file – this example stores the FileName in the
      //title property)
      document.getElementById('filesToIgnore').value += (imgToDelete.title + ","); 
      //Additional code here to remove the thumbnail
      imgToDelete.style.display = "none";
}

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 “filesToIgnore” field within your Page Load or related event:

C#
//Upload click event
protected void btnUpload_Click(object sender, EventArgs e)
{
  //Get files to be ignored (not uploaded)
  string[] ignoredFiles = filesToIgnore.Value.Split(new char[]{','}, 
                          StringSplitOptions.RemoveEmptyEntries);
  //Iterate through posted files
  HttpFileCollection uploadFiles = Request.Files;
  for (int i = 0; i < uploadFiles.Count; i++)       
  {             
    HttpPostedFile postedFile = uploadFiles[i];
    //If it isn't a file meant for deletion - don't upload             
    if (!ignoredFiles.Any(c => postedFile.FileName.Contains(c)))
    {
      //Upload your file here
      Response.Write(String.Format("{0} Uploaded!<br />",postedFile.FileName));
    }
  }
}

Other Considerations

Although this example was a very hastily-created one, there are many methods of handling this. You may want to seriously consider using one of the many jQuery-based Plugins 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 can often be great at handling File Upload operations as well; although many people (myself included) cringe at the sight of that five-letter F-word.

I’ll throw an example project up here soon.

License

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


Written By
Software Developer (Senior)
United States United States
An experienced Software Developer and Graphic Designer with an extensive knowledge of object-oriented programming, software architecture, design methodologies and database design principles. Specializing in Microsoft Technologies and focused on leveraging a strong technical background and a creative skill-set to create meaningful and successful applications.

Well versed in all aspects of the software development life-cycle and passionate about embracing emerging development technologies and standards, building intuitive interfaces and providing clean, maintainable solutions for even the most complex of problems.

Comments and Discussions

 
-- There are no messages in this forum --