ASP.NET Hosting :: ASP.NET File Upload Control
- by mbridge
The asp.net FileUpload control allows a user to browse and upload files to the web server. From developers perspective, it is as simple as dragging and dropping the FileUpload control to the aspx page. An extra control, like a Button control, or some other control is needed, to actually save the file.
<asp:FileUploadID="FileUpload1"runat="server"/>
<asp:ButtonID="B1"runat="server"Text="Save"OnClick="B1_Click"/>
By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.
<httpRuntimemaxRequestLength="8192"executionTimeout="220"/>
From code behind, the mime type, size of the file, file name and the extension of the file can be obtained. The maximum file size that can be uploaded can be obtained and modified using the System.Web.Configuration.HttpRuntimeSection class.
Files can be alternatively saved using the System.IO.HttpFileCollection class. This collection class can be populated using the Request.Files property. The collection contains HttpPostedFile class which contains a reference to the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using System.Web.Configuration;
namespace WebApplication1
{
public partial class WebControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Using FileUpload control to upload and save files
protected void B1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength >
0)
{
//mime type of the uploaded file
string mimeType = FileUpload1.PostedFile.ContentType;
//size of the uploaded file
int size = FileUpload1.PostedFile.ContentLength; // bytes
//extension of the uploaded file
string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
//save file
string path = Server.MapPath("path");
FileUpload1.SaveAs(path + FileUpload1.FileName);
}
//maximum file size allowed
HttpRuntimeSection rt = new HttpRuntimeSection();
rt.MaxRequestLength = rt.MaxRequestLength * 2;
int length = rt.MaxRequestLength;
//execution timeout
TimeSpan ts = rt.ExecutionTimeout;
double secomds = ts.TotalSeconds;
}
//Using Request.Files to save files
private void AltSaveFile()
{
HttpFileCollection coll = Request.Files;
for (int i = 0; i < coll.Count; i++)
{
HttpPostedFile file = coll[i];
if (file.ContentLength > 0)
;//do something
}
}
}
}