dotnetspider.com


 


TutorialsForumResourcesReviewsJobsInterviewVideosCommunitiesProjectsTraining

Subscribe to Subscribers


Online MembersSunitha
Prasad kulkarni
Prabu Thangavelu
chaminda
sravan
cloud
Shesh Kumar Mishra
Gajanan
pavan
Anu George
somasekar
More...




Resources » Code Snippets » ASP.NET WebForms


FileUpload control in ASP.NET web form using c#


Posted Date:     Category: ASP.NET WebForms    Rating: 1 out of 5
Author: Member Level: Gold    Points: 12 (Rs 12)


FileUpload is very simple control allows user to select file and upload.
You can easily handle that with very little coding and ease. I have given the full code behind for this functionality.

First create a aspx page with 3 controls

FileUpload: rename it to FileUpload1
Label: rename it to lblMsg
Button: rename it to btnAdd

Copy this code in your code behind file inside the class declaration. As you can see we are simply calling the
SaveUploadedFile() function to save the uploaded file. you can check for the particular extension within the function
right now we are checking for only 3 extensions. You can change it in sAllowedExt string.

Here is the code behing stuff:


String UPLOAD_PATH = "";
int MAXSIZE = 5 * 1024 * 1024; // max 5 MB

String sAllowedExt = ",.doc,.pdf,.xls,"; // make sure whatever extension you enter, string ends with comma

protected void Page_Load(object sender, EventArgs e)
{
btnUpload.Attributes.Add("onclick", "return checkFile();");
UPLOAD_PATH = Server.MapPath("~/UploadedDocs") + "/";
}

private void setMsg(String sMsg)
{
lblMsg.Text = sMsg;
}

protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
SaveUploadedFile();
}
catch (Exception ex)
{
//Response.Write("Error: " + ex.Message);
setMsg("File could not be uploaded successfully.");
}
}

private void SaveUploadedFile()
{

if (FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String validExt = ;
if (validExt.IndexOf("," + fileExtension + ",") != -1)
{
if (FileUpload1.FileBytes.Length <= MAXSIZE)
{
FileUpload1.PostedFile.SaveAs(UPLOAD_PATH + FileUpload1.FileName);
setMsg("File uploaded successfully.");
}
else
{
setMsg("File size exceeded the permitted limit.");
}
}
else
{
setMsg("This file type is not accepted.");
}
}

}


Once the user uploads the file, it's availabe using FileUpload.PostedFile.SaveAs() method.
You can then directly save that file to particular folder with new name. We are checking FileUpload1.HasFile
to make sure we only process if a file is uploaded.

Make sure to change the max. request length attribute in web.config file to handle large files. here is the example
which can handle quite large files. Change as per your need.


< system.web >
< httpRuntime maxRequestLength="2048576" executionTimeout="54000" / >
< /system.web >


The javascript function is added in Load event just to validate the FileUpload1 control. Here is the same.

function checkFile()
{
if( document.getElementById("FileUpload1").value == "" || document.getElementById("FileUpload1").value == null )
{
alert("Please select a file.");
return false;
}
else return true;
}


Hope this easy to use solution will be useful in your web application.

Go Upload...


Did you like this resource? Share it with your friends and show your love!





Responses to "FileUpload control in ASP.NET web form using c#"
Author: Pradeep Iyer    30 Apr 2009Member Level: Gold   Points : 0
Hi,

Thanks for posting this.

Very useful one :)

Regards,
Pradeep Y (DotNetBeginnersHeaven)



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: Track visitors using ASP.NET
    Previous Resource: How to find the control name from Object sender in C#?
    Return to Resources
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    (No tags found.)

    My Profile

    Active Members
    TodayLast 7 Daysmore...


    Awards & Gifts


    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds



    About Us    Trademark Disclaimer    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.