Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Feb 3, 2003

Uploading a file on the server

Uploading a file from the client to the server is very straightforward with ASP.NET. Just use the <input type="file" runat="server"> tag and its wrapper class HtmlInputFile. Here's how you define the control on the page:

<form runat="server" enctype="multipart/form-data">
  Select a file to upload:<br>
  <input type="file" runat="server" ID="Uploader">
  <input type="button" runat="server" ID="Upload" value="Upload" 
    OnServerClick="Upload_Click">
</form>
And here's the code you write in the code-behind file (or in the page's <script> section) to handle the button's Click event:

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 Try
End 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 <httpRuntime> setting in the application's web.config file. The size is specified in KB, so <httpRuntime maxRequestLength="8192" /> sets the maximum file size on 8MB.
Marco Bellinaso
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date