Uploading of File
When we are talking about uploading of file, we mean to say upload file physically and save into a particular location in server. We can also upload file that means save file into database. Let us first examine how we can upload file physically in a particular location in server. The code snippet has been written in c#.
Figure1:

In ASP.NET, we can do the file upload using HTML Input (File) control (as shown in above figure: Figure1). In order to start the process we need to follow the following basic steps:
Step I: Add the control:
Code: HTML
<input id="FileUpload" type="file" runat="server"/>
Code: HTML
<form id="frmUpload" enctype="multipart/form-data" runat="server">
Code: CSharp
FileUpload.PostedFile.SaveAs("D:\\FileStorage\\UploadedFile");
- We may check file type and allow user to upload some specific file only;
- We may allow user to upload upto a maximum size of file;
- We may check the length of file and disallow user to upload empty file etc.
How to check file type?
Code:
System.IO.Path.GetExtension(FileUpload.PostedFile.FileName);//It will give the extension of file and thus help to identify file type.
Code:
if(FileUpload.PostedFile.ContentLength<=5242880) //5242880 bytes i.e., restricted upto 5mb
Code:
if(FileUpload.PostedFile.ContentLength>0) //File should not be empty by checking size of uploaded file in bytes

How to upload multiple file:
In order to upload multiple file we can simply take multiple input file control. But if we don't want to use multiple input file control instead keep one input file control only, here is the solution:
Code: CSharp
ArrayList arrayList = new ArrayList();
arrayList.Add(FileUpload);
foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in arrayList)
{
HIF.PostedFile.SaveAs("D:\\FileStorage\\UploadedFile");
}
In web.config :
Code: CSharp
<httpRuntime maxRequestLength="20000"/>
Download of File:
Once we save the file into file storage server or into database, we need to think about download of the uploaded file .Here I am describing how we can download file from physical storage server (see Figure2):
Code: CSharp
protected void btnDownload_Click(object sender, EventArgs e)
{
string fileName = "MyFile.txt";
System.IO.FileStream fs = null;
fs = System.IO.File.Open("D:\\FileStorage\\UploadedFile\\MyFile.txt ", System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
fs = null;
}
Figure3:

In my forthcoming article I will discuss how to save physical file into database.
Conclusion:
So we have seen upload of files and how to download uploaded file. Uploading and downloading files is very common in real life application


