File Upload to Server with ASP.net

File Upload to Server with ASP.net Uploading file to server from client sometimes very tricky. Sometimes it is required that you will not upload file more than certain size. This is the step by step approach to upload file from client to server.

Step 1: Add html input type as file

<input id =”uploadFile” type=”file” runat=”server” />

Step 2: Create a button to upload file in the server

<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click”  />

Step 3: Create a folder in the web project like “TempFiles”
Step 4: Upload file in the server.

protected void Button1_Click(object sender, EventArgs e)
{

if (this.uploadFile.PostedFile != null)
{
// Get a reference to PostedFile object
HttpPostedFile huploadFile = uploadFile.PostedFile;

// Get size of uploaded file
int nFileLen = huploadFile.ContentLength;

decimal fileSize = uploadFile.PostedFile.ContentLength / 1024;
if (fileSize > 100) //If file size is no more than 100 KB
{
this.lblMsg.Text = "Size of this image is greater than 100KB";
return;
}

byte[] scriptData = new byte[nFileLen];

// Read uploaded file from the Stream
huploadFile.InputStream.Read(scriptData, 0, nFileLen);

string filePath = Server.MapPath("TempFiles");

filePath = filePath + "\\" + Path.GetFileName(uploadFile.PostedFile.FileName); //concate filename with file path
FileStream newFile = new FileStream(filePath, FileMode.Create);

// Write data to the file
newFile.Write(scriptData, 0, scriptData.Length);

// Close file
newFile.Close();
}
else
{
lblMsg.Text = "This is an empty file";

}
}
Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>