File upload in ASP.NET using C#
Create a web form with an addition attribute EncType=”Multipart/Form-Data” added to your form tag. Put a HtmlFileInput control into the form by adding the tag <input type=”file” id=”file1″ runat=”server” NAME=”file1″ /> and also add a button to upload the file and a label to give the message to the user.
In the click event script, you will reference to the posted file through the PostedFile property of your HtmlFileInput control. Say you can get the full client path of the file by using file1.PostedFile.FileName if file1 is the id of your HtmlFileInput control.
To get simply the file name, not the client full path, you have to process the file name using the GetFileName() static method in the System.IO.Path class. This would trim the file name to simply file1.txt, for example. Finally to save the file into the server file system, you have to use the SaveAs() method of the PostedFile object, as given below:
file1.PostedFile.SaveAs(Server.MapPath("./") + strFileName);
sample code:
<%@ Page Language="C#" Debug="true" %>
<script language="C#" runat="server">
private void btnUpload_Click(Object sender, EventArgs e)
{ string strFileName = file1.PostedFile.FileName;
strFileName = System.IO.Path.GetFileName(strFileName);
file1.PostedFile.SaveAs(Server.MapPath("./") + strFileName);
lblMsg.Text = "Your file: " + strFileName + " has been uploaded successfully !";
}
</script>
<html>
<body>
<h2>ASP.NET Upload using C#</h2>
<form EncType="Multipart/Form-Data" method="post" runat="server" ID="Form2">
<input type="file" id="file1" runat="server" NAME="file1"/>
<asp:Button id="btnUpload" OnClick="btnUpload_Click" Text="Upload!" runat="server" />
<asp:Label id="lblMsg" runat="server" />
</form>
</body>
</html>
