File Upload Control
File upload control allows your users to upload files to the web application using a web browser. Exercise caution in granting anyone to upload files. You may want to use the asp.net 2.0 membership features to restrict access only to specific users.
Open a new website in visual studio and drag and drop the upload control on to the designer surface. As you can see the file upload has 2 parts, the text box and a browse button.
You can already test the control to see that clicking the browse button opens up the select file dialog where you can browse through the files in your hard drive and select the particular file you want to upload. What we need to do now is add a new button on to the designer surface (call it "bttnUpload"). And in the OnClick event of the upload button we will write on how to save the data into a folder on our server. Remember to create a folder by name "Uploads" in the root where we are going to upload the files. So the aspx code finally looks like
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="bttnUpload" OnClick="bttnUpload_Click"
runat="server" Text="Upload" />
</div>
In the code behind for the "bttnUpload" button click we will write the following code
protected void bttnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Uploads"),FileUpload1.FileName);
if (File.Exists(fileName))
File.Delete(fileName);
FileUpload1.SaveAs(fileName);
}
}
What we are essentially doing in the above code is checking to see if a file is selected to be uploaded (HasFile property). We then upload and save the file in the specified directory (using the saveas method).


0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home