ASP.NET File Uploadingby Budi Kurniawan
File upload and download are much simpler tasks in ASP.NET than in classic ASP, thanks to the extensive .NET Framework class library. File upload in ASP.NET is as easy as retrieving an HTML form value. In classic ASP, it's a somewhat involved process, in which you have to extract the content of the uploaded file from raw HTTP request data. In the end, many ASP programmers resort to a third-party component for file upload.
File download is even easier in ASP.NET with the new
WriteFile method in the Request object. Sending a file to the browser can be achieved using a single line of code. In classic ASP, you have to open the file yourself and send a number of bytes at a time. With file download, however, the same problem remains as in classic ASP and other Web technologies. Many Web programmers still wonder how they can force the browser to display the Download dialog. Sending the file with the
WriteFile method will not necessarily display the dialog. The default behavior for browsers is that if the file's MIME type is recognized, the browser will either try to display the content or it will fire up an application associated with that MIME type. This "smart" behavior is often not the desired behavior. In this article, I will show you how to force the browser to always show the Download dialog, so the user can save the file to disk.
After some theory, this article will present a file upload and download utility you can use to manage files on your server. You can download all of the files for this article, including the image files, here.
To force the browser to display the Download dialog, you need to set the Response object's
ContentType property to
application/octet-stream and add an HTTP Request header called
Content-Disposition with the following value:
attachment; filename="filename" where filename is the default filename that will be displayed in the Download dialog at the browser.
Therefore, to send a file to the browser, the first thing to do is to write the following code:
Response.ContentType = "application/octet-stream" Response.AddHeader("Content-Disposition", _ "attachment; filename=""" & filename & """")
Afterwards, you can send the file to the browser using the Response object's
WriteFile method. You must not send anything before and after sending the file content. It is usually a good idea to clear the buffer prior to sending the file.
The code in Listing 1 displays all the files in the
C:\temp directory. The code in Listing 2 does the actual sending of the file to the browser.
Listing 1. Displaying the list of files
<%@ Import Namespace="System.IO"%> <html> <head> <title>File Download</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) Dim root As String = "C:\temp\" Dim files() As String = Directory.GetFiles(root) Dim sb As New StringBuilder(2048) Dim f As String For Each f In files Dim filename As String = Path.GetFileName(f) sb.Append("<br><a href=FileDownload.aspx?file=") sb.Append(root).Append(Server.UrlEncode(filename)) sb.Append(">").Append(filename).Append("</a>") Next fileList.Text = sb.ToString() End Sub </script> </head> <body> <form runat="server"> <asp:Label id="fileList" runat="server"/> </form> </body> </html>
The code in Listing 1 only has one event handler:
Page_Load. It first obtains all the file names
in the specified directory (
C:\temp) and puts them in an array of strings called
Dim files() As String = Directory.GetFiles(root)
It then constructs a
StringBuilder object as the output buffer.
Dim sb As New StringBuilder(2048) Dim f As String
Next, it iterates all of the files in the array and constructs a hyperlink of the following format for each file in the directory.
pathis the full physical path of the file on the server.
For Each f In files Dim filename As String = Path.GetFileName(f) sb.Append("<br><a href=FileDownload.aspx?file=") sb.Append(root).Append(Server.UrlEncode(filename)) sb.Append(">").Append(filename).Append("</a>") Next fileList.Text = sb.ToString()
An important point is the use of the
System.Web.HttpServerUtility classes to encode the file path so that it will be safely transferred in the URL.
To send the file itself, you need
FileDownload.aspx, shown in Listing 2.
Listing 2. FileDownload.aspx
<%@ Import Namespace="System.IO"%> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) Dim root As String = "C:\temp\" Dim filepath As String = Request.Params("file") If Not filepath Is Nothing Then If File.Exists(filepath) And filepath.StartsWith(root) Then Dim filename As String = Path.GetFileName(filepath) Response.Clear() Response.ContentType = "application/octet-stream" Response.AddHeader("Content-Disposition", _ "attachment; filename=""" & filename & """") Response.Flush() Response.WriteFile(filepath) End If End If End Sub </script>
To perform file upload in ASP.NET, you need to know two classes: the
System.Web.UI.HtmlControls.HtmlInputFile class and the
System.Web.HttpPostedFile. The first class represents an HTML control that the user uses to select a file on the client side and upload it. The latter represents the uploaded file itself, and an instance of this class is obtained from the
HtmlInputFile control. The next two subsections discuss each class in detail.
The HtmlInputFile ClassThe
System.Web.UI.HtmlControls.HtmlInputFileclass is very simple and easy to use. It defines the following four properties:
Accept: a comma-separated list of MIME types the user can select to upload.
MaxLength: the maximum length of the uploaded file path. This property has nothing to do with the uploaded file itself.
PostedFile: Returns a
System.Web.HttpPostedFileobject, representing the uploaded file.
Size: The width of the text box that displays the selected file. Again, this has nothing to do with the size of the uploaded file.
To use the
HtmlInputFile control, the containing form must have the
enctype="multipart/form-data" defined. Here is an example of how to use the
HtmlInputFile control in a Web form.
<form enctype="multipart/form-data" runat="server"> Select File to Upload: <input id="uploadedFile" type="file" runat="server"> <input type=button id="upload" value="Upload" OnServerClick="Upload_Click" runat="server"> </form>
The HttpPostedFile Class
This class represents an uploaded file. It has one method,
SaveAs, that saves the uploaded file in the specified location on the server. In addition, it has the following four properties:
ContentLength: the length of the uploaded file.
ContentType: the content type of the uploaded file.
FileName: the client-side file path of the uploaded file. Note that browsers under Windows include the file path information, whereas browsers under Linux/Unix and Macintosh don't.
System.IO.Streampointing to the uploaded file.
Pages: 1, 2