Tuesday, February 19, 2008

File Upload

There are two ways to upload a file in ASP.NET:

If Not hiddenFile.PostedFile Is Nothing And hiddenFile.PostedFile.ContentLength > 0 Then

Dim fn As String = System.IO.Path.GetFileName(hiddenFile.PostedFile.FileName)

Dim SaveLocation As String = Server.MapPath("images") & "\" & fn

Try

hiddenFile.PostedFile.SaveAs(SaveLocation)

Response.Write("The file has been uploaded.")

Catch Exc As Exception

Response.Write("Error: " & Exc.Message)

End Try

Else

Response.Write("Please select a file to upload.")

End If



Dim myFile As HttpPostedFile = hiddenFile.PostedFile 'or you can use Request.Files("hiddenFile")

If myFile IsNot Nothing Then

Dim nFileLen As Integer = myFile.ContentLength

If nFileLen > 0 Then

Dim myData As Byte() = New Byte(nFileLen - 1) {}

myFile.InputStream.Read(myData, 0, nFileLen)

Dim strFilename As String = Path.GetFileName(myFile.FileName)

WriteToFile(Server.MapPath(strFilename), myData)

End If

End If


Private Sub WriteToFile(ByVal strPath As String, ByRef Buffer As Byte())

Dim newFile As New FileStream(strPath, FileMode.Create)

newFile.Write(Buffer, 0, Buffer.Length)

newFile.Close()

End Sub


If you take a look at the SaveAs method of HttpPostedFile using reflector, you will notice that the above two methods of uploading file are the same.


Public Sub SaveAs(ByVal filename As String)

If (Not Path.IsPathRooted(filename) AndAlso RuntimeConfig.GetConfig.HttpRuntime.RequireRootedSaveAsPath) Then

Throw New HttpException(SR.GetString("SaveAs_requires_rooted_path", New Object() {filename}))

End If

Dim s As New FileStream(filename, FileMode.Create)

Try

Me._stream.WriteTo(s)

s.Flush()

Finally

s.Close()

End Try

End Sub

File Upload with ASP.NET

How to upload a file to a Web server in ASP.NET by using Visual Basic .NET

blog comments powered by Disqus