You are currently browsing the daily archive for December 13th, 2007.

Objective: This article gives step by step instructions how to create a flexible and sophisticated image upload application that prefixes the file name with a unique ID, it enforces file size and file type restrictions, checks for upload problems, displays success and or error message, displays the uploaded file type, file size, and file location, displays all uploaded images present in the upload folder and shows their truncated file names. Uses pure asp.net server side code for the upload function with additional client side validation to stop execution of the form if no file is present.

Background: It is safe to say that almost all sophisticated web applications with backend functionality require image or file upload capabilities. To write such an application is not too difficult once you understand its mechanism, but for the beginning asp.net developer it can be one of those hair pulling, eye poking and other types of chain yanking experiences that drains the life force (Chi) and leaves a person old before his or her time. I have searched for weeks online for an example of how this is done and to this date I have not found one that would feel like a complete, well rounded application. After much self inflicted injury as mentioned above, I whipped up something that I know you are going to love.

Procedure: Follow instructions below to accomplish this task. This article uses Visual Web Developer Express 2008.

  1. Let’s start by creating a new empty web site in VB and name it MyImageUpload.
  2. Create a new web form in your site and name it FileUpload.aspx. Don’t use code behind so you can better see how the puzzle fits together without having tab back and forth between pages.
  3. Now let’s go into code view and add an important name space that allows our upload to work. Copy and paste the following under the page directive at the top of the page:

    <%@ Import Namespace=”System.IO” %>

  4. Now let’s create a new folder in our site and name it UploadFolder. This is where our uploaded images will be stored.
  5. Let’s go into code view and copy and paste the following code between the Form tags of your page. These are the visual elements on the page. Go over it line by line to get an idea what’s going on. It won’t make complete sense until we have our “code behind” code in place which will be our next step.

    <!-- File upload server control -->
    <asp:FileUpload
    ID="upImage"
    runat="server"/>
    <br />
    
    <!-- Client Side Required Field Validator for the File Upload server control -->
    <!-- Making sure the form is not submitted unless a file has been selected -->
    <asp:RequiredFieldValidator
    ID="RequiredFieldValidator1"
    runat="server"
    ControlToValidate="upImage"
    ErrorMessage="Please select a file first!"
    SetFocusOnError="True"
    Display="Static" style="font-size: small" >
    </asp:RequiredFieldValidator>
    
    <br />
    
    <!-- This is the Upload Submit Button to initiate the upload process -->
    <asp:Button
    ID="btnAdd"
    Text="Upload Image"
    OnClick="btnAdd_Click"
    runat="server" />
    
    <!-- This Label displays the upload success or error message -->
    <asp:Label
    ID="lblMsg"
    runat="server"
    style="color: #FF0000; font-size: small;" />
    <br />
    
    <!-- This Label displays the uploaded file's type i.e. JPG, PNG etc. -->
    <asp:Label
    id="lblFileContentType"
    runat="server"
    style="color: #808080;font-size: small;" />
    <br />
    
    <!-- This Label displays the uploaded file's size in KB -->
    <asp:Label
    id="lblFileSize" 
    
    runat="server"
    style="color: #808080;font-size: small;" />
    <br />
    
    <!-- This label displays the uploaded file's location on the server relative to the root -->
    <asp:Label
    id="lblFileLocation"
    runat="server"
    style="color: #808080;font-size: small;" />
    <br />
    
    <!-- This is the DataList that displays all uploaded images present in the UploadImages folder -->
    <!-- Take a look at the subprocedure on top "display uploaded images" to understand how it works -->
    <!-- Notice below how the Substring property is used to truncate the image names -->
    <asp:DataList
    ID="dlstImages"
    RepeatColumns="6"
    runat="server">
        <ItemTemplate>
            <asp:Image
            ID="Image1"
            ImageUrl='<%# Eval("Name", "~/UploadImages/{0}") %>'
            Style="width: 100px; margin:5px;"
            runat="server" />
            <br />
            <asp:Label
            ID="Label1"
            runat="server"
            Text='<%#Eval("Name").Substring(0, 15) & " ..."%>'
            ToolTip='<%#Eval("Name")%>'
            style="color: #808080;font-size: x-small"
            >
            </asp:Label>
        </ItemTemplate>
    </asp:DataList>

  6. OK, now copy and paste the following code between the script blocks on top. These are all the procedures and functions that creates our application. I put it inside text box because the code is too wide to display properly in a table. Go over the code line by line and read all the comments until everything makes sense. Try to change or modify the code based on your assumptions and test it in your browser to see what happens.
    '.......................File Upload Button Click Event Start.......................
    'create subprocedure for upload button click event
    'if the file upload field is not empty then
    'declare the maximum allowable file size as whatever bytes
    'declare a variable fileSize and set it equal to the file size of the uploading image
    'if the file exceeds the maximum allowable size then
    'end the upload and display the warning message
    'else
    'declare the GUID and set it equal to GUID function created below
    'if the file extension complies with CheckFileType function then
    'declare the upload file path and set it equal to the name of the folder & GUID & file name
    'save the image to the file path
    'display upload success message
    'display file type extension
    'display file size
    'display the location of the saved file
    'else
    'display upload aborted message
    'display a zero for all other labels
    'end all if statements
    'end subprocedures Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
    
        If (upImage.HasFile) Then
            Dim maxFileSize As Integer = 1024000 'adjust max. file size as needed
            Dim fileSize As Integer = upImage.PostedFile.ContentLength
            If fileSize > maxFileSize Then
                lblMsg.Text = "File size exceeded the maximum limit of " & maxFileSize / 1024 & " Kb."
            Else
                Dim strGuid = fnGuid()
                If (CheckFileType(upImage.FileName)) Then
                    Dim filePath As String = "~/UploadImages/" & strGuid & upImage.FileName
                    upImage.SaveAs(MapPath(filePath))
                    lblMsg.Text = "File Upload Success!"
                    lblFileContentType.Text = "File type: " & upImage.PostedFile.ContentType
                    lblFileSize.Text = "File size: " & CStr(upImage.PostedFile.ContentLength / 1024) & " Kb"
                    lblFileLocation.Text = "File Location: /UploadImages/" & strGuid & upImage.FileName Else
                    lblMsg.Text = "Wrong file type! Upload Aborted."
                    lblFileContentType.Text = "File type: 0"
                    lblFileSize.Text = "File size: 0"
                    lblFileLocation.Text = "File Location: 0"
                End If
            End If
        End If
    End Sub
    '.......................File Upload Button Click Event End.......................
    
    '................Function To Check For Valid File Extension Start................
    'declare a function as true or false boolean to check for file type extension to be allowed
    'declare a variable named "ext" as a string and set it equal to the extention of the file to be uploaded
    'if this file extension matches .gif .png .jpg or .jpeg then set the boolean to True (allow it)
    'otherwise set the boolean to False (do not allow it)
    'end the conditional statement
    'end the function Function CheckFileType(ByVal fileName As String) As Boolean
        Dim ext As String = Path.GetExtension(fileName)
        Select Case ext.ToLower()
            Case ".gif" ' add or remove file types as needed
                Return True
            Case ".png"
                Return True
            Case ".jpg"
                Return True
            Case ".jpeg"
                Return True
            Case Else
                Return False
        End Select
    End Function
    '................Function To Check For Valid File Extension End................
    
    '..................Function To Create GUID For File Name Start.................
    'declare a function to create a GUID based on the current date and time to be added to the _
    'file extension of the uploaded file so as to make it unique.
    'declare a variable named strGuid and set it equal to nothing for now
    'using the try exception handling, set the strGuid variable equal to current date and time
    'if there is a problem creating the GUID, throw an exception
    'end try
    'return the generated GUID
    'end the function
    Function fnGuid() As String
        Dim strGuid As String = ""
        Try
            With Today
                strGuid = .Year & .Month & .Day & Now.Hour & Now.Minute & Now.Second End With
        Catch ex As Exception
            Throw ex
        End Try
        Return strGuidEnd Function
    '..................Function To Create GUID For File Name End.................
    
    '................Subprocedure To Display Uploaded Images Start...............
    'create a sub procedure to display uploaded images
    'declare a variable named upfolder and set it equal to the path of the uploaded images folder
    'declare a variable named dir as the directory info of the uploaded images folder
    'create a datasource from the contents of this directory/folder
    'and bind to each image in the folder
    Sub Page_PreRender()
        Dim upFolder As String = MapPath("~/UploadImages/")
        Dim dir As New DirectoryInfo(upFolder)
        dlstImages.DataSource = dir.GetFiles()
        dlstImages.DataBind()
    End Sub'................Subprocedure To Display Uploaded Images End...............
    

  7. That’s it! Enjoy.

    upload-complete