Not logged in - Login

Upload file from a web page

The following describes how to create a web page in ASP.Net to upload a file to the web server.

Step 1: Create a web page with a FileUpload control on it. Optionally, add a required field validator to the page.

<!-- The File Upload control -->
<asp:FileUpload ID="fileUploadSample" runat="server" />

<!-- The Required Field Validator -->
<asp:RequiredFieldValidator ID="valUploadSample" runat="server" 
   ErrorMessage="Please choose a file to import first." Display="Dynamic" 
   ControlToValidate="fileUploadSample" Font-Bold="True"></asp:RequiredFieldValidator>

<!-- Add a button to allow the user to start the processing -->
<asp:Button ID="btnUploadFile" runat="server" 
   Text="Upload File"
   OnClick="btnUploadFile_Click" />

Step 2: Add code to the code behind page to do the processing

protected void btnUploadFile_Click(object sender, EventArgs e)
{
   // declare a variable to hold the name of the file name. 
   string sTempFile = null;

   // create a temporary file name
   sTempFile = System.IO.Path.GetTempFileName();

   // call the method on the FileUpload control to save the selected file to temporary file location.
   this.fileHolidayImport.SaveAs(sTempFile);

   // make sure the file was uploaded.
   if (!System.IO.File.Exists(sTempFile))
   {
      // give some indication back to the user that the file could not be uploaded
      return;
   }




   // --------------------------------------------------
   // do something with the uploaded file
   // --------------------------------------------------




   // It may be a good idea to have this bit inside of a finally{} section of a try-catch-finally block.
   // make sure we have a file name and the file exists
   if (!string.IsNullOrWhiteSpace(sTempFile) && System.IO.File.Exists(sTempFile))
   {
      // we're done with the file, delete it.
      System.IO.File.Delete(sTempFile);
   }
}