| |
Overview
Not so long ago uploading a file from a client browser to the server was a quite tedious task. Developers often had to use third party tools or write their own file upload utilities. With the development of ASP.NET writing a file upload script is a piece of cake! This example will illustrate how this is done. It will display an HTML form from which the user will select a file to upload. Once the user clicks the upload button, properties like its size, source and destination names are displayed.
HTML Form
The following form will accept a file name and then we will need submit to an aspx file:
<form runat="server" enctype="multipart/form-data">
<table>
<tr>
<td>Select File :</td>
<td><input type="file" id=file1 runat="server" /></td>
</tr>
<tr>
<class=tagname>td><asp:Button id=btn1 runat="server" text="Upload"
onclick="upload"/>
</td>
</tr>
</table>
</form>
|
Functionality Code
| |
<%@ page language="vb" %> |
| |
<%@ import namespace="System" %> |
| |
<%@ import namespace="System.Web" %> |
<script language="vb" runat="server" > public sub page_load(s as object,e as eventargs) response.write ("<h1>devhood.com - File Upload ASP.NET Way...</h1>") end sub public sub upload(s as object,e as eventargs) dim s1 as string dim s2 as string dim pos as integer s1=file1.postedfile.filename pos=s1.lastindexof("\") +1 s2=s1.substring(pos) file1.postedfile.saveas (request.servervariables ("APPL_PHYSICAL_PATH") & "general\" & s2) response.write("<strong>File has been uploaded as " & request.servervariables("APPL_PHYSICAL_PATH") & s2 & " !</strong>") response.write("<h4>Client File Name : " & file1.postedfile.filename & "</h4>") response.write("<h4>File Size : " & file1.postedfile.contentlength & "</h4>") response.write("<h4>Content Type : " & file1.postedfile.contenttype & "</h4>") end sub </script> <% if page.ispostback=false then %> <form runat="server" enctype="multipart/form-data"> <table> <tr> <td>Select File :</td> <td><input type="file" id=file1 runat="server" /></td> </tr> <tr> <class=tagname>td><asp:Button id=btn1 runat="server" text="Upload" onclick="upload"/> </td> </tr> </table> </form> <% end if %>
|
Note that ENCTYPE type attribute is set to "multipart/form-data"; also the control is set to run at the server side.
|
|