Uploading Files Using a Webform
 
Published: 07 Jun 2004
Unedited - Community Contributed
Abstract
If you require a quick simple upload function for you web based application you can accomplish this action by using the System.IO namespace along with the default namespaces that are added when you create a webform within Visual Studio.NET
by Steven Swafford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 18301/ 22

Building Your File Upload Webform

[Download Code]

Once you have added a new webform to your project you are ready to add the necessary components.

First, drag a file field component onto your web form. Second, drag a button on your web form. Finally, drag a label onto your web form. You can name each of these components as you desire. Once you have accomplished these steps you should see something along these lines:

Web Form Design

Now let us move on to the code that will process the file uploads.

The Code-Behind To Handle File Uploads

[Download Code]

Now you should see something along the lines of the following when viewing the page in your browser:
Web Form

The code behind is as follows:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
 
namespace FileUpload
{
 /// <summary>
 /// Summary description for FileUpload.
 /// </summary>
 public class FileUpload : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Label uploadLblMessage;
  protected System.Web.UI.WebControls.Button cmdUploadFile;
  protected System.Web.UI.WebControls.Label FileUploadTexLabel;
  protected System.Web.UI.HtmlControls.HtmlInputFile FileToUpload;
      
  string strFileDirectory = "C:\\temp\\";
      
  private void Page_Load(object sender, System.EventArgs e)
  {
  }
 
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
             
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
   this.cmdUploadFile.Click += new System.EventHandler(this.cmdUpload_Click);
   this.Load += new System.EventHandler(this.Page_Load);


  }
  #endregion


  private void DeleteExistingFile (string strFileName)
  {


   if (strFileName.Trim().Length > 0)
   {
    FileInfo fileToDelete = new FileInfo(strFileName);
    
    //if file exists then we will delete it
    if (fileToDelete.Exists)
    {     
     fileToDelete.Delete();
    }
   }
  } 
 
  private void cmdUpload_Click(object sender, System.EventArgs e)
  {


   //determine file name to be uploaded
   string strFileName = System.IO.Path.GetFileName(FileToUpload.PostedFile.FileName);


   if (( FileToUpload.PostedFile != null) && (FileToUpload.PostedFile.ContentLength > 0))
   {
    try
    {             
     //Save File to the server
     FileToUpload.PostedFile.SaveAs(strFileDirectory + strFileName);
     uploadLblMessage.Visible = true;
     uploadLblMessage.Text = "File: " + strFileDirectory + strFileName + " Uploaded Successfully";
    }
    catch(Exception ex)
    {
     uploadLblMessage.Visible = true;
     uploadLblMessage.Text = ex.Message;
     DeleteExistingFile(strFileDirectory + strFileName);
    }
   }
   else
   {
    uploadLblMessage.Text = "Select a file to upload. Please Try Again!";
   }


  }
 }
}

When you attempt to upload a file you will be notified if the upload was a success or failure. Here is an example:
Upload Status

You could of course expand on this and limit the file size of uploads, creating unique directories to hold uploads for any given user, and sending out notification via email when a new upload occurs. I hope this example finds a use during you development process.



User Comments

Title: System.NullReferenceException: Object reference not set to an instance of an object.   
Name: Janet
Date: 2005-03-01 12:06:33 PM
Comment:
Hi.. I have converted the codes to vb.net. However, when the upload button is clicked i got the following error "System.NullReferenceException: Object reference not set to an instance of an object."

Could you help me out.. thanks
Title: Priner friendly version - followup   
Name: Steven
Date: 2004-12-09 5:22:16 PM
Comment:
If you look below there is a link for the printer friendly version. HTH....
Title: Priner friendly version   
Name: Jim@CSCsupport.com
Date: 2004-12-09 5:07:17 PM
Comment:
It would be nice if you would make a Printer Friendly option available on your site or if you limited the width of your program code lines so they would fit when I printed
your web page to my printer from a scren with a 1024X768
display setting. Otherwise I lose part of the code.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 9:21:45 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search