ASP.NET 4.0 comes with a FileUpload control that allows you to send a file from your computer to a Web server. The file to be uploaded is submitted to the server as part of the browser request during postback. After the file has completed uploading, you can manage the file in your code.
1. Create an ASP.NET project in Visual Studio 2010.
2. Drag and drop a FileUpload control on Web Form.
3. Write this code on the Page Load event of the Web Form. You need to make sure your folder on the Web Server is set to a valid directory and have write permissions on it.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Boolean fileOK = false;
String path = Server.MapPath("~/UploadedFilesFolder/");
if (FileUpload1.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions =
{".gif", ".png", ".jpeg", ".jpg"};
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
FileUpload1.PostedFile.SaveAs(path
+ FileUpload1.FileName);
Label1.Text = "File uploaded!";
}
catch (Exception ex)
{
Label1.Text = "File could not be uploaded.";
}
}
else
{
Label1.Text = "Cannot accept files of this type.";
}
}
}
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
Arvind tomarPosted Jun 18, 2014, 3:10 AM
It work's good into localhost but when I try to upload something into my web server it's give my an error(authentication). What can I do now. Please help
Former memberPosted Sep 30, 2012, 1:21 PM
This is really nice article http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=5&title=Fileupload%20Control%20In%20Asp.net
VEERA sekharPosted Jan 19, 2011, 2:20 AM
this article must be require asp button.