In ASP.NET 2.0, the FileUpload control enables users to upload file from your web pages. The FileUpload control consists of a text box and a browse button. Clicking on the button allow users to select a file on the client and upload it to the server. Let us first start off by exploring how to upload a single file in asp.net. To do so, follow these steps:
Step 1: Drag and drop the FileUpload server control from the toolbox. The code behind looks as follows :
<asp:FileUpload id=”FileUpload1” runat=”server” />
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
}
VB.NET
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)End Sub
Step 4: Add the following code to the event handler
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("MyFiles") +
"\\" + FileUpload1.FileName);
}
}
catch (Exception ex)
{
// Handle your exception here
}
}
VB.NET
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
If FileUpload1.HasFile Then
FileUpload1.SaveAs(Server.MapPath("MyFiles") & "\" & FileUpload1.FileName)
End If
Catch ex As Exception
' Handle your exception here
End Try
End Sub
Try
If FileUpload1.HasFile Then
FileUpload1.SaveAs(Server.MapPath("MyFiles") & "\" & FileUpload1.FileName)
End If
Catch ex As Exception
' Handle your exception here
End Try
End Sub
The “HasFile” property of our FileUpload control helps us to determine if a file has actually been uploaded. We then use the "SaveAs" method to save the file to disk.
That is all you require to implement the FileUpload functionality in your web pages. In order to retrieve the metadata information of the file being uploaded, you can drop a Label control on to the form designer and use the PostedFile.FileName and PostedFile.ContentLength on the FileUpload control. This would give you the uploaded file’s name and size respectively. Eg:
Label1.Text = FileUpload1.PostedFile.FileName;
Label1.Text += FileUpload1.PostedFile.ContentLength;
Uploading Multiple Files
So far so good. Let’s extend the above sample to upload multiple files at a time. Follow these steps mentioned below to do so:
Step 1: Drag and drop multiple (in our case four) FileUpload controls on to the designer.
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
}
VB.NET
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)End Sub
Step 4: Import the System.IO namespace.
using System.IO; - C#
Imports System.IO - VB.NET
Step 5: Use the ‘HttpFileCollection’ class to retrieve all the files that are uploaded. Files are encoded and transmitted in the content body using multipart MIME format with an HTTP Content-Type header. ASP.NET extracts this information from the content body into individual members of an HttpFileCollection.
The code would look as follows:
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
Path.GetFileName(hpf.FileName));
}
}
}
catch (Exception ex)
{
// Handle your exception here
}
}
VB.NET
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("MyFiles") & "\" & Path.GetFileName(hpf.FileName))
End If
Next i
Catch ex As Exception
' Handle your exception here
End Try
End Sub
Try
' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("MyFiles") & "\" & Path.GetFileName(hpf.FileName))
End If
Next i
Catch ex As Exception
' Handle your exception here
End Try
End Sub
The ‘HttpPostedFile’ class provides methods and properties to access the contents and properties of each file. In our case, we use this class to check the length of the file. To retrieve the filename and length of the file uploaded, we can use hpf.FileName and hpf.ContentLength respectively.
Well, that was simple to implement, wasn’t it! However there are a few points to be kept in mind.
Some important points to consider while uploading
1. To save a file to the server, the account associated with ASP.NET must have sufficient permissions on the folder, where the files are being uploaded. This would usually be the ‘ASPNET’ account for Windows XP or a similar OS. In Windows Server 2003, the account used is ‘NETWORKSERVICE’. So you would be required to explicitly grant write permissions to these accounts on the folder.
2. While uploading the files to a remote server, the default ASPNET user account used by ASP.NET does not have network permissions by default. The solution is to either give the account such permissions or use impersonation to have it run under a different account that has the permissions.
3. By default, you can upload no more than 4096 KB (4 MB) of data. However there is a workaround for this limitation. You can change the maximum file size by changing the maxRequestLength attribute of the httpRuntime element in the web.config file. You can also increase the ‘
executionTimeout’
. By default it is 110 seconds. I would encourage you to experiment with the other attributes of the httpRuntime element.
<configuration>
<system.web>
<httpRuntime
executionTimeout="200"
maxRequestLength="8192"
requestLengthDiskThreshold="256"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false"/>
</system.web>
</configuration>
References
There are a number of good resources I referred to, for this article. A few of them are:
http://www.wrox.com/WileyCDA/Section/id-292160.html
http://msdn2.microsoft.com/en-US/library/aa479405.aspx
http://msdn2.microsoft.com/en-us/library/system.web.httpfilecollection.aspx
Conclusion
File uploading in ASP.NET has certainly improved from its earlier versions. However we as developers would like to perform way better than it does today. In this article, I made an attempt to use this control to upload multiple files to the server. I hope this article was useful and I thank you for viewing it.
No comments:
Post a Comment