Uploading Multiple Files

Uploading Multiple Files
March 6, 2016 Comments Off on Uploading Multiple Files NET sourav
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

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;
About The Author