Wednesday, March 26, 2014

Upload a file in an ASP.NET web forms application.

This may be a more modern way to go, but I have found, today (while tinkering), in my notes an example of how to do an old school file upload implementation in ASP.NET web forms. To test the code in my notes, I made an new web forms app in Visual Studio 2013 and I put these two controls in Default.aspx:

  1. <input id="FileUploader" type="file" runat="server" />
  2. <asp:Button ID="Button" runat="server" Text="Button" OnClick="Button_Click" />

 
 

I then fleshed out the code behind like so which allowed me to move files into C:\temp successfully via the controls mentioned above:

using System;
using System.Web.UI;
namespace Pushy
{
   public partial class _Default : Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
      }
      
      protected void Button_Click(object sender, EventArgs e)
      {
         string fileName = FileUploader.PostedFile.FileName;
         int fileLength = FileUploader.PostedFile.ContentLength;
         if (fileName != "" && fileLength > 0 && fileLength <= 2048000)
         {
            fileName = System.IO.Path.GetFileName(fileName);
            try
            {
               FileUploader.PostedFile.SaveAs("C:\\temp\\" + fileName);
            }
            catch (UnauthorizedAccessException exception)
            {
               throw exception;
            }
         }
      }
   }
}

No comments:

Post a Comment