18 April 2007

FileUpload Control


Before start using this code:

  • Create a folder called UploadFiles at the root of your web site. This is where you'll upload your files.

  • Run this page in a web browser to find out what's your MaxRequestLength value. The code will be executed on page load event and the result will be displayed when the page loads completely.

  • MaxRequestLength value is the maximum size for a file to be uploaded successfuly.




<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)

If Not (Page.IsPostBack) Then
Dim section As New System.Web.Configuration.HttpRuntimeSection
Dim value As Integer = section.MaxRequestLength
Response.Write("MaxRequestLength: " & value)
End If

End Sub


Protected Sub FileUploader_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles FileUploader.Load

Dim serverFilePath As String = Server.MapPath("~/UploadFiles/")
Dim fileIsGood As Boolean = False

If FileUploader.HasFile Then

Dim fileExtension As String =
System.IO.Path.GetExtension(FileUploader.FileName).ToLower()
Dim defaultExtensions As String() = {".jpg", ".jpeg", ".png", ".gif"}

For i As Integer = 0 To defaultExtensions.Length - 1
If fileExtension = defaultExtensions(i) Then
fileIsGood = True
End If
Next

If fileIsGood Then
Try
FileUploader.PostedFile.SaveAs(serverFilePath & FileUploader.FileName)
Me.ErrorLabelFileUpload.Text = "Your image was uploaded!"
'// Optional: display the path and the file name of the uploaded file
Me.FileNameLabel.Text = serverFilePath & FileUploader.FileName

Catch ex As Exception
Me.ErrorLabelFileUpload.Text = "Your image could not be uploaded."
End Try

Else
Me.ErrorLabelFileUpload.Text = "Please select a valid image file!"
End If
End If
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Upload files to server</title>
</head>
<body>
<form id="AppMainForm" runat="server">
<div>
</div>
<div>
<asp:FileUpload ID="FileUploader" runat="server" Width="430px" />
<br />
<asp:Button ID="FileUploadButton" runat="server" Text="Upload" />
<br />
<br />
<asp:Label ID="ErrorLabelFileUpload" ForeColor="Red" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="FileNameLabel" runat="server" ForeColor="Black"></asp:Label>
</div>
</form>
</body>
</html>

No comments: