Uploading a file to the web server using ASP.NET 2.0

For anyone who has ever had to do this before, knows it has always been a pain. In ASP.NET, it is about as easy as it gets. Here is a quick overview of what you need to do.

 

Create a new page, say UploadFile.aspx. Edit the HTML for that page, change the <form> tag to look like this:

 

<form id="Form1" method="post" runat="server"

encType="multipart/form-data">

 

Note, you just need to add the encType. That tells the server, that when you submit this form, it’s going to be a multi-part MIME document.

 

Then add that special HTML item for selecting the file to download:

 

<input id="fileUpload" type="file" name="fileUpload" runat="server">

 

Then a submit button:

 

<asp:Button id="Button1" runat="server" Text="Upload File"></asp:Button>

 

Then go to the event for that button click and add this code:

 

if ( fileUpload.PostedFile.ContentLength > 0 )

{

      try

      {

            string strFileName;

            HttpPostedFile postedfile = Request.Files[0];

            strFileName = postedfile.FileName;

            strFileName = strFileName.Substring(strFileName.LastIndexOf("")+1);

            strFileName = Server.UrlDecode(strFileName);

            fileDoc.PostedFile.SaveAs(Server.MapPath("./upload/") + strFileName);

            this.lblMsg.Text = "File copied to server successfully! " + FormatBytes(fileDoc.PostedFile.ContentLength);

            this.lblMsg.ForeColor = Color.Green;

      }

      catch (Exception ee)

      {

            this.lblMsg.Text = "Error copying file: " + ee.Message;

            this.lblMsg.ForeColor = Color.Red;

      }

}

 

I also use this little function a lot to format bytes in KB, MB, etc..

 

private string FormatBytes(long bytes)

{

      string strOutput = "";

 

      if ( bytes > 0 ) strOutput = string.Format("{0} bytes",bytes);

      if ( bytes > 1000 ) strOutput = string.Format("{0:N1} KB",bytes / 1024);

      if ( bytes > 1000000 ) strOutput = string.Format("{0:N1} MB",bytes / 1024 / 1024);

      if ( bytes > 1000000000 ) strOutput = string.Format("{0:N2} GB",bytes / 1024 / 1024 / 1024);

 

      return strOutput;

}

 

That’s about all there is to it – VERY simple compared to how it used to be!! Enjoy.

Posted in ASP.NET, Uncategorized

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

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 4 other followers

%d bloggers like this: