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.

<!-- 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 :

<!-- 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?

//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

//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:HiddenField ID="filesToIgnore" runat="server" />

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

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:

//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 that the sight of that five-letter F-word.

I’ll throw an example project up here soon.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s