Upload Files : Basic PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

This short tutorial teaches how to add a file upload functionality to your ASP.NET page. Unlike in classical ASP, where you have to install some server component to accomplish the upload task, now in ASP.NET this functionality is intrinsic.

Make a web form as usual, with an addition attribute EncType="Multipart/Form-Data" added to your <form ID="Form1"> tag. Put a HtmlFileInput control into the form by adding the tag: <input type="file" id="MyFile" runat="server" NAME="MyFile" /> With an upload button and a label for 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 MyFile.PostedFile.FileName if MyFile 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 myfile.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 in this example:

MyFile.PostedFile.SaveAs(Server.MapPath("./") + strFileName);

There are two points worth notice:

1) Remember to set the file permission on your server to allow write for IUSR_ServerName account.

2) Using the SaveAs()

part is put into a try block so as to handle whatever problem that may encounter during the upload process, like disk permission and disk space limitation.

Here are the complete code:

<%@ Page Language="C#" Debug="true" %>
<script language="C#" runat="server">
private void btnUpload_Click(Object sender, EventArgs e) {
string strFileName = MyFile.PostedFile.FileName;
strFileName = System.IO.Path.GetFileName(strFileName);
MyFile.PostedFile.SaveAs(Server.MapPath("./") + strFileName);
lblMessage.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="lblMessage" runat="server" />
</form>
</body>
</html>
 
< Prev   Next >
School Joomla Templates and Joomla Tutorials