.Net ASP.Net – Uploading File To Server

2 Comments

Here is a small snippet of code that will allow visitors to your website to upload files to your server.

This code will open an OpenFileDialog box to allow the user to select a file.

<asp:TableCell>
     Select File:
     <input id="uplTheFile" type="file" runat="server" style="width: 476px; height: 26px" />
</asp:TableCell>

This code will add a button to the form to upload the file.

<asp:TableCell>
     <asp:Button ID="cmdUploadFile" value="Upload" runat="server" Text="Upload" OnClick="cmdUploadFile_Click" />
</asp:TableCell>

cmdUploadFile_Click Event

protected void cmdUploadFile_Click(object sender, EventArgs e)
{
     string strFileNameOnServer = uplTheFile.PostedFile.FileName;
     string appDataPath = HttpContext.Current.Server.MapPath("~/App_Data");

     if (string.IsNullOrEmpty(strFileNameOnServer))
     {
           lblInformation.Text = "Error - a file name must be specified.";
           return;
     }

     if (uplTheFile.PostedFile != null)
     {
          try
          {
               uplTheFile.PostedFile.SaveAs(appDataPath + "\\" + strFileNameOnServer);
          }
          catch (Exception ex)
          {
               lblInformation.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>.  " + ex.Message;
          }
      }
}

This will upload the file into the App_Data folder of the website.

Tags: ,

2 Responses to “ASP.Net – Uploading File To Server”

  1. Marcell Scarlett Says:

    Good Content. Post more! :)

  2. canon eos 600d kit Says:

    Semmi bajom a cikk, de nem értek egyet néhány pontot néhány extenct. Én valószínűleg egy kisebbségi, bár, lol. Köszönöm megosztására.

Leave a Reply