ASP.NET File Upload
Introduction
With plain, old ASP uploading a file from client browser to the server was a tedious task. Developers either used some third party controls or wrote their own file upload utilities. ( Remember BinaryRead and searching of crlf pairs? :-) With ASP.NET the situation has changed now writing file upload script is very easy task. Just few properties and a method and your file is uploaded !
This example illustrates with an example how to write simple file uploading form using ASP.NET. The example simply displays a HTML form in which user can select a file to upload. Once user clicks on Upload button the file is Uploaded to the server and its details like Size, Source and Destination File names are shown.
A Sample HTML Form
First, you need a form which will accept a file name and then submit to an aspx file. You need to use HTML File control for that purpose.
Example of such form is given below :
<form runat="server" enctype="multipart/form-data">
<table>
<tr>
<td>Select File :</td>
<td><input type="file" id=file1 runat="server" /></td>
</tr>
<tr>
<td><asp:Button id=btn1 runat="server" text="Upload"
onclick="upload"/>
</td>
</tr>
</table>
</form>
Please note the following points :
- Form ENCTYPE type attribute is set to "multipart/form-data"
- FILE control is used which has in built functionality of displaying file selection dialog box. The control is set to run at server side
Code Behind the functionality
The actual file upload operation is performed in fileupload.aspx file which has following 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>BipinJoshi.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>Your 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>
<td><asp:Button id=btn1 runat="server"
text="Upload" onclick="upload"/>
</td>
</tr>
</table>
</form>
<%
end if
%>
10/23/2007 11:35:53 PM
Category
File Uploading
Back