File uploading with ASP.NET HtmlForms

By · June 12, 2012 · 0 comments

Following up on my previous article about ASP.NET HtmlForms, this sample code illustrates how to handle file uploads. As you can see the usual ASP.NET server side methods work perfectly well even if you don't use an ASP.NET file upload control.

Test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input id="fupFile" name="fupFile" type="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>


Test.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
HttpPostedFile file = Request.Files["fupFile"];
if (file != null && file.ContentLength > 0)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", filename)));
}
}
}
}
}

Get the latest posts delivered to your inbox.

Comments

There are no comments yet. Be the first to leave a comment!

Leave a Comment

All comments are moderated and rel="nofollow" is in use. Avatars are sourced from gravatar.com – a globally recognised avatar.

Type the numbers from the picture above

About me
John Avis ...mostly about web development and programming, with a little bit of anything else related to the Internet, computers and technology.

profile for John at Stack Overflow, Q&A for professional and enthusiast programmers
Subscribe

Get the latest posts delivered to your inbox. *