Friday, March 20, 2009

How to upload multiple files using ASP.Net?

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Fileupload.aspx.vb" Inherits="Fileupload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html>
< head>
< title>Multiple File Upload</title>
< /head>
< body>
< form id="Form1" method="post" enctype="multipart/form-data" runat="server">
< h1>
ASP.NET Multiple File Upload Example</h1>
< p>
Select the Files to Upload to the Server:
< br>
< input id="File1" type="file" name="File1" runat="server">
< /p>
< p>
< input id="File2" type="file" name="File2" runat="server"></p>
< p>
< input id="Btnupload" type="submit" value="Upload Files" name="BtnUpload" runat="server" >
< /p>
< /form>
< asp:Label ID="ResultMsg" runat="server" Visible="False" ForeColor="#ff0033">< /asp:Label>
< /body>
< /html>

=======================


Imports System.IO

Partial Class Fileupload
Inherits System.Web.UI.Page

Protected Sub Btnupload_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btnupload.ServerClick

Dim ResultMessage As String = ""
Dim Filename As String
Dim extension As String

'Variable FolderName where the files will be saved
Dim FolderName As String = "D:/AJAXVBWEB/Temp/"
'Variable to hold the File
Dim objFile As HttpPostedFile
'Variable used in the Loop
Dim i As Integer
Try
'Loop Through the Files
For i = 0 To Request.Files.Count - 1

'Get the HttpPostedFile
objFile = Request.Files(i)
'Check that the File exists has a name and is not empty
If Not (objFile Is Nothing Or objFile.FileName = "" Or objFile.ContentLength < 1) Then

'Get the name of the file
Filename = objFile.FileName
Filename = Path.GetFileName(Filename)
extension = Path.GetExtension(Filename)

'Creates the folder if it does not exists
If (Not Directory.Exists(FolderName)) Then
Directory.CreateDirectory(FolderName)
End If

'Save each uploaded file
objFile.SaveAs(FolderName & Filename)

'Assign the File Name and File Type to Result
ResultMessage = ResultMessage & "Uploaded File: " & objFile.FileName & " of type " & objFile.ContentType & "
"

End If
Next

'If no files where selected provide a user friendly message
If ResultMessage = "" Then
ResultMessage = "Select atleast one file to upload."
End If

Catch errorVariable As Exception
ResultMessage = errorVariable.ToString()
End Try

'Unhide the Result Label
ResultMsg.Visible = True
'Assign the Result to ResultMsg Label Text
ResultMsg.Text = ResultMessage

End Sub
End Class

No comments:

 
Feedback Form