File uploading with .NET
One of the new additions in .NET is the ability to upload files without the need for additional components. The class HttpPostedFile deals with posted files. It has only a few members, but these cover anything you would want to do with and upload. Here is an example that hopefully demonstrates everything you need to know.
The one thing that you must remember when uploading files, is to set the encoding type. If you do not, it will not upload the file.
2 | <form id="Form1" method="post" runat="server" enctype="multipart/form-data" action="/code/2/upload.aspx"> |
So how easy is it to up load the file? Very easy, it can be done in just one line. In the supplied example, the class is copied into a variable for clarity, as it will be referred to numerous times, so it takes three lines.
11 | Dim File As HttpPostedFile |
21 | File = Request.Files.Get(0) |
30 | File.SaveAs(Server.MapPath("....filesuploaddeleteme.txt")) |
Note: The user ASPNET must have write access to the target directory if you wish to save the file.
A nice feature of the class if that the files size and type are available without having to save the file to disk. In the example, this is used to stop large files and files that cannot be displayed in the page.
23 24 25 26 27 28 29 30 31 | If File.ContentLength > 1024 Then ErrorMsg.Text = "File is bigger than 1k" Else If File.ContentType <> "text/plain" Then ErrorMsg.Text = "File is not a text file" |
The ContentType is set using the files MIME type, not the extension and recognizes most popular file formats.
So, all you want to do is process the file for the user or put it into a database, why bother saving it if you do not have to. The class gives you access to the upload stream which can be read just like any stream.
35 36 37 38 39 40 41 42 43 44 45 | Dim sr As System.IO.StreamReader Dim strContent As String sr = New System.IO.StreamReader(File.InputStream) 'display contents FileContents.Text = sr.ReadToEnd sr.Close() |
Note: If you wish to access the uploaded file as a stream and also want to save it to disk, save it first, as there is a slight lag when closing the stream which may cause the saved file to be empty.



















