Wednesday, November 30, 2011

How to upload a file in asp.net using c#

Title:How to use upload control in asp.net

Description:
We can say "Sending file from client system to server system" as a definition .Mostly this control can be used as in  practical for uploading resume,image and attachment towards email.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>How to upload a file in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpLoad id="Fud" AlternateText="You cannot upload files" runat="server" />
<asp:Button id="btnupload" Text="Upload File" OnClick="btnupload_Click" runat="server" />
<asp:Label runat="server" Id="lblmessage" />
</form>
</body>
</html>

The properties and methods of File upload:

*has file--true-->File is upload
false-->File is not uploaded
*posted file--content type-->it returns file types
text/plain--->normal text file
text/xml---->XML file
application/msword-->doc file
save as(file path)--->it will save upload file in server system
Here i will shown to allow user to upload photos(image file type of gif) .For this i have taken file upload control and button server control in aspx page.


Code behind:

protected void btnupload_Click(object sender, EventArgs e)
{
Response.write(Fud.Hasfile);
Response.write(Fud.filename);
Response.write(Fud.posted file contenttype);
if(Fud.Hasfile)
{
if(Fud.Postedfile.ContentType=="image/gif")
{ 
Fud.postedfile.saveAs(server.mappath(".")+"\\"+Fud.filename);
lblmessage.text="upload successfully";
}
else
lblmessage.text="upload gif file";
}
else
lblmessagetext="file required";
}
}
Note:File upload control supports maximum of 4mb file size for uploading to server

No comments:

Bel