Master C# Logo banner
Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 


File Uploader

Add Comment
 

 
Download File SDK
fileuploader.zip (3kb) .NET v1 (v1.0.3705)

Introduction
While making websites which accept data from its users, sometimes there is a need to allow the user upload files to the Server. To solve this problem I have written this example to help to do just that. Even though its installation procedure might seem a bit difficult to new web developers, people who have done this before in any other language will find it very simple. Unlike ASP you do not need to purchase a separate component anymore, ASP.NET has inbuilt server-controls that make this job very easy for you.

Explanation
To upload files the System.Web.UI.HtmlControls namespace has a class called HtmlInputFile . This class exposes the properties of the traditional <input type="file"> control.
HtmlInputFile class contains a property called PostedFile which returns an instance of the class HttpPostedFile. This class has various methods which help us to get various attributes of the posted file. Also the HttpPostedFile class exposes a method SaveAs which saves the posted file to your server.

Requirements
1) .NET SDK v1.0.3705 (Note: This code might not run on future versions of the SDK)
2) Web Server supporting ASP.NET with sufficient security permissions.

Installation Instructions:
1) Unzip the zip file in to any directory (Remember to keep 'Use folder names' checked ON in your unzipping program.)
2) Customize the look and color of the file by opening it in any text editor.
3) Find out in which directory does your server allows write access to files (eg. on the www.brinkster.com server it is the '/db' directory ).
Without write access you cannot upload to any server.
If you server has some other directory then
Open 'FileUpload.aspx' file in a text editor and change the path of "upload" on to whatever path your server allows and save the file.
4) Upload the all files to your server
5) That's great you have setup the file upload page !!!!
6) Then call the file http://urserver.com/FileUpload.aspx in your browser and upload your files...

Code
1) FileUpload.aspx :- The File Upload Page

<%@ Import Namespace="System.IO" %>
<%@ page Language="C#" debug="true"  %>
<html>
 <head>
  <title>File Upload , By Saurabh Nandu - http://www.MasterCSharp.com</title>
  <script language="C#" runat="server">
   //This method is called when the 'upload' button is pressed
   public void UploadFile(object sender , EventArgs E)
   {
    //check if the file posted is not null
    if(myFile.PostedFile!=null)
    {
      //Get the filename only
      string newnm = Path.GetFileName( myFile.PostedFile.FileName ) ;

      //save the file to the destination path on your server
      //change this path as per your needs
      //Remember the path you specify should exist and have 'write' access
      myFile.PostedFile.SaveAs(Server.MapPath("upload") + "\\" + newnm) ;

      //Get the various properties of the Uploaded file
      fname.Text=myFile.PostedFile.FileName;
      fenc.Text=myFile.PostedFile.ContentType ;
      fsize.Text=myFile.PostedFile.ContentLength.ToString();
    }
   }
  </script>
 </head>
<body>
  <center>
   <h3> File Upload Demo , by Saurabh Nandu </h3>
 <!-- It is very Important to specify enctype="multipart/form-data"
  or the form won't work -->
<form method="post" action="FileUpload.aspx" enctype="multipart/form-data"
   runat="server" >

	<table border="1" cellspacing="2" cellpadding="2" >
	<tr> <td><h5>Select the File to upload</h5></td</tr>
	<tr><td>
	<input type="file" id="myFile" runat="server" >
	</td></tr>
	<tr><td>
	<input type="button"  value="Upload" OnServerClick="UploadFile"
          runat="server" >
	</td></tr>
	</table>
	</form>
	<br>
	<br>
	<table border="1" cellspacing="2">
	<tr><td><b>File Details</b></td>
	<td>&nbsp;</td>
	</tr>
	<tr>
	<td>File Name :</td>
	<td><asp:label id="fname" text="" runat="server" /></td></tr>
	<tr>
	<td>File Encoding :</td>
	<td><asp:label id="fenc" runat="server" /></td></tr>
	<tr>
	<td>File Size :(in bytes)</td>
	<td><asp:label id="fsize" runat="server" /></td></tr>
	</table>
	</center>
</body>
</html>

 

2) A interesting manipulation you could do is to limit the size of the file uploaded to 1 mb.
(Note: This code is not included in the downloaded code.) (Only relevant code shown)

<script language="C#" runat="server">
   //This method is called when the 'upload' button is pressed
   public void UploadFile(object sender , EventArgs E)
   {
    //check if the file posted is not null
    //Say we want to limit the size of File uploaded by the
    //user to 1Mb (i.e.1048567bytes)
    if(myFile.PostedFile!=null&&myFile.PostedFile.ContentLength<=1048567)
    {
      //Get the filename only
      string newnm = Path.GetFileName( myFile.PostedFile.FileName ) ;

      //save the file to the destination path on your server
      //change this path as per your needs
      //Remember the path you specify should exist and have 'write' access
      myFile.PostedFile.SaveAs(Server.MapPath("upload") + "\\" + newnm) ;

      //Get the various properties of the Uploaded file
      fname.Text=myFile.PostedFile.FileName;
      fenc.Text=myFile.PostedFile.ContentType ;
      fsize.Text=myFile.PostedFile.ContentLength.ToString();
    }
    else
    {
	//Assume we have a label with the Id errormes to display the error
	errormes.Text="You have uploaded a File which
                        exceeds the 1mb Limit" ;
   }
  </script>

You can also place multiple HtmlInputFile controls on the same page to allow your clients upload more than one file at a time. Another interesting property the HttpPostedFile object exposes is InputStream, which gets the Stream to the uploaded file, so incase you want to save the Uploaded File directly to the database, you can use this property and save the file directly to the binary field of the database.

In order to protect you from DOS (Denial of Service) attacks Microsoft has by default limited the the size of the file that can be uploaded to under 4 Mb. In case you want to upload files larger than 4 Mb you will have to make specific changes in the machine.config (in order to affect all file upload scripts on the server) or the web.config (in order to affect just the file upload script in the current application) file. Locate or add the following section in the config file. The maxRequestLength is the property you should be updating to reflect the maximum file size that can be uploaded in bytes.
As you can see below the default is set to allow only 4 Mb ( 1 Mb = 1024 bytes ).

<Configuration>
  <system.web>
    <httpRuntime
       maxRequestLength="4096" />
  </system.web>
<Configuration>

Conclusion
This example demonstrates the power of the HtmlInputFile server-control that provides you with a flexible way of uploading files to the server.

Comments

Add Comment