This ASP.NET (C#) example shows how to receive one or more uploaded files from a single HTTP upload. The uploaded files may be accessed in-memory, or saved to files on the web server.
First, here’s the HTML page that uploads the files to the web server:
<html>
<body>
<form method="POST" enctype="multipart/form-data" action = "http://localhost/ReceiveUpload.aspx" >
<input name=hid1 type=hidden value="test123">
<input name=hid2 type=hidden value="abcdef">
<input name=attach1 type=file size=20><br>
<input name=attach2 type=file size=20><br>
<input type=submit value="Upload">
</form>
</body>
</html>
The server-side code to receive the upload is in two parts: ReceiveUpload.aspx and ReceiveUpload.aspx.cs:
ReceiveUpload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReceiveUpload.aspx.cs" Inherits="ReceiveUpload" %>
<!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>C# to Receive Uploaded Files</title>
</head>
<body>
<div id="divContent" runat="server">>
This will be replaced in the Page_Load (below).
</div>
</body>
</html>
ReceiveUpload.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ReceiveUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection uploadFiles = Request.Files;
// Build HTML listing the files received.
string summary = "<p>Files Uploaded:</p><ol>";
// Loop over the uploaded files and save to disk.
int i;
for (i = 0; i < uploadFiles.Count; i++)
{
HttpPostedFile postedFile = uploadFiles[i];
// Access the uploaded file's content in-memory:
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
// Save the posted file in our "data" virtual directory.
postedFile.SaveAs(Server.MapPath("data") + "\\" + postedFile.FileName);
// Also, get the file size and filename (as specified in
// the HTML form) for each file:
summary += "<li>" + postedFile.FileName + ": "
+ postedFile.ContentLength.ToString() + " bytes</li>";
}
summary += "</ol>";
// If there are any form variables, get them here:
summary += "<p>Form Variables:</p><ol>";
//Load Form variables into NameValueCollection variable.
NameValueCollection coll = Request.Form;
// Get names of all forms into a string array.
String[] arr1 = coll.AllKeys;
for (i = 0; i < arr1.Length; i++)
{
summary += "<li>" + arr1[i] + "</li>";
}
summary += "</ol>";
divContent.InnerHtml = summary;
}
}