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#.
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:
<input id="FileUpload" type="file" runat="server"/>
<form id="frmUpload" enctype="multipart/form-data" runat="server">
- 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?
System.IO.Path.GetExtension(FileUpload.PostedFile.FileName);//It will give the extension of file and thus help to identify file type.
if(FileUpload.PostedFile.ContentLength<=5242880) //5242880 bytes i.e., restricted upto 5mb
if(FileUpload.PostedFile.ContentLength>0) //File should not be empty by checking size of uploaded file in bytes
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:
ArrayList arrayList = new ArrayList();
foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in arrayList)
In web.config :
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):
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));
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/octet-stream";
fs = null;
In my forthcoming article I will discuss how to save physical file into database.
So we have seen upload of files and how to download uploaded file. Uploading and downloading files is very common in real life application