devxlogo

Uploading a file on the server

Uploading a file on the server

Uploading a file from the client to the server is very straightforward with ASP.NET. Just use the tag and its wrapper class HtmlInputFile. Here’s how you define the control on the page:

Select a file to upload:

And here’s the code you write in the code-behind file (or in the page’s

Sub Upload_Click(ByVal sender As Object, ByVal e As EventArgs)    If Not Uploader.PostedFile Is Nothing Then        Try            ' retrieve the destination dir path            Dim destDir As String = Server.MapPath("./Upload")            ' extract the filename part from the full path of the posted file            Dim fileName As String = System.IO.Path.GetFileName _                (Uploader.PostedFile.FileName)            ' combine the destination directory with the filename            Dim destPath As String = System.IO.Path.Combine(destDir, fileName)            ' save the file on the server            Uploader.PostedFile.SaveAs(destPath)            Response.Write("Thanks for submitting your file")        Catch exc As Exception            Response.Write(exc.Message)        End TryEnd Sub

Note that in order to handle the uploading of a file, the form must have the enctype attribute set to multipart/form-data, as you see above. Also note that by default the maximum size of the uploaded file is 4MB. If you try to upload a bigger size you'll get a runtime error. You may want to increase this value, for example because you have ZIP, AVI or MP3 files bigger than 4MB. To do so, set the maxRequestLength attribute of the setting in the application's web.config file. The size is specified in KB, so sets the maximum file size on 8MB.

devx-admin

Share the Post: