Click here to Skip to main content
15,897,273 members
Articles / Web Development / ASP.NET

ASP.NET File Uploader with Overwrite Message

Rate me:
Please Sign up or sign in to vote.
4.42/5 (8 votes)
3 Dec 2008CPOL3 min read 55.2K   923   42  
Intranet file upload dialog box with overwrite prompt and file archiving.
Imports System
Imports System.IO
Imports System.Web.Configuration
Imports System.Web.Services
Imports System.Web.Script.Services

Partial Public Class _Default
    Inherits System.Web.UI.Page

#Region " Public variables "

    Dim gstrMessageText As String = "Click Browse to select a file to upload."

#End Region

#Region " Page Load "

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            'get the folder from the calling form variable
            Dim strFolder As String = Request("folder")
            If strFolder = "" Then
                strFolder = CStr(WebConfigurationManager.AppSettings("UploadDirectory"))
            End If
            ViewState("Folder") = strFolder
            'save dest to hidden form element so file exists check looks at server file
            Me.hDestFolderPath.Value = ParseDestFilePath(strFolder)
            'save to label so user sees dest folder
            Me.lblFolder.Text = strFolder

            Dim strArchive As String = Request("archive")
            If strArchive = "" Then
                strArchive = CStr(WebConfigurationManager.AppSettings("ArchiveDirectory"))
            End If
            ViewState("archive") = strArchive
            'set the return info in hidden variables
            Me.hReturnForm.Value = Request("retForm")
            Me.hReturnField.Value = Request("retField")
            ViewState("retform") = Request("retForm")
            ViewState("retfield") = Request("retField")
            'get Overwrite type form request
            Me.hOverwrite.Value = Request("overwrite")
            ViewState("overwrite") = Request("overwrite")

            'set java events to change button states
            uploadFile.Attributes.Add("onkeydown", "javascript:FileBrowseChangeMessage();")
            uploadFile.Attributes.Add("onmouseout", "javascript:FileBrowseChangeMessage();")

            'set cursor for disabled buttons
            Me.uploadFile.Style.Add("cursor", "hand")
            Me.btnSave.Style.Add("cursor", "default")
            Me.btnClose.Style.Add("cursor", "default")
            Me.lblUploadMessage.Text = gstrMessageText

        Else

        End If

        Me.uploadFile.Focus()


    End Sub

#End Region

#Region "File Uploader"

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        'upload file to file system
        Dim sDestFullPathName As String = ""
        Dim sDestFolder As String = ParseDestFilePath(ViewState("Folder"))
        If uploadFile.HasFile Then
            'select app dir or website root according to webconf setting
            'check if folder exists on server - should never error because programmer has set folder in calling program
            If Not Directory.Exists(sDestFolder) Then
                'should never happen
                Me.lblUploadMessage.ForeColor = Drawing.Color.Red
                Me.imgBeforeMessage.ImageUrl = "~/Images/icon_caution.gif"
                Me.lblUploadMessage.Text = "Upload folder not found!  Please call support."
                Exit Sub
            End If
            'save viewstate so filename can be sent back to calling page
            sDestFullPathName = sDestFolder & "\" & uploadFile.FileName
            ViewState("UploadFileName") = sDestFullPathName
            ViewState("SourceFileName") = uploadFile.PostedFile.FileName
        End If
        If sDestFullPathName > "" Then
            'notify user that file typed in is invalid - not able to get working
            'asp.net cannot access client machines
            'If Not File.Exists(uploadFile.PostedFile.FileName) Then
            'Me.lblUploadMessage.ForeColor = Drawing.Color.Red
            'Me.lblUploadMessage.Text = "File not found!  Please check file name."
            'Exit Sub
            'End If

            'upload file if file type is defined in web.config
            If CheckFileType(sDestFullPathName) Then
                Me.imgBeforeButtons.Visible = True 'show the uploader animation
                If ViewState("archive") > "" And Me.hFileExists.Value = "true" Then
                    'file exists on server and archive folder set
                    If Not doOverwriteArchive(uploadFile.FileName) Then
                        'should never happen
                        Me.imgBeforeButtons.Visible = False
                        Me.btnCancelOverwrite.Visible = False
                        Me.btnCancel.Visible = True
                        Exit Sub
                    End If
                End If
                'do upload
                Me.uploadFile.SaveAs(sDestFullPathName)
                'set form controls
                SetButtonsAfterUpload(sDestFullPathName)
                'set hidden field values for returning to calling page
                Dim ReturnFullPath As String = CStr(WebConfigurationManager.AppSettings("ReturnFullPath"))
                Me.hReturnFileName.Value = sDestFullPathName
                If ReturnFullPath.ToLower = "no" Then
                    Me.hReturnFileName.Value = ViewState("Folder") & "/" & uploadFile.FileName
                End If
                Me.hReturnForm.Value = ViewState("retform")
                Me.hReturnField.Value = ViewState("retfield")
            Else
                Me.lblUploadMessage.ForeColor = Drawing.Color.Red
                Me.lblUploadMessage.Text = "Invalid file type!"
            End If
        Else
            Me.lblUploadMessage.ForeColor = Drawing.Color.Red
            Me.lblUploadMessage.Text = "Please select a file before clicking upload" & _
                " and be sure file contains data."
        End If
        Me.imgBeforeButtons.Visible = False
    End Sub

    Private Function doOverwriteArchive(ByVal UploadFileName As String) As Boolean
        'overwrite existing file - Archives old file if option set
        'Archive old file if Archive directory is set in web.conf
        Dim sDestFullPathName As String = ViewState("UploadFileName")
        Dim strArchiveDir As String = SelectArchiveFolder()
        If strArchiveDir = "error" Then
            Exit Function
        End If
        'upload to archive
        If strArchiveDir > "" Then
            'check if folder exists on server - should never error because programmer has set folder in calling program
            If Not Directory.Exists(strArchiveDir) Then
                'should never happen
                Me.lblUploadMessage.ForeColor = Drawing.Color.Red
                Me.imgBeforeMessage.ImageUrl = "~/Images/icon_caution.gif"
                Me.lblUploadMessage.Text = "Archive folder not found!  Please call support."
                Return False
            End If
            Dim strArchiveFilePathName As String = strArchiveDir & "\" & TimeStampFile(UploadFileName)
            Me.uploadFile.SaveAs(strArchiveFilePathName)
        End If
        Return True
    End Function

    Function CheckFileType(ByVal fileName As String) As Boolean
        'verify file extensions
        Dim strFileTypes As String = CStr(WebConfigurationManager.AppSettings("FileTypes"))
        Dim strExt As String = Path.GetExtension(fileName).ToLower()
        If strFileTypes.IndexOf(strExt) > -1 Then
            Return True
        End If
        Me.lblUploadMessage.ForeColor = Drawing.Color.Red
        Me.lblUploadMessage.Text = "File must me a valid file type.  Please select another File."
        Return False
    End Function

#End Region

#Region " Cancel Overwrite button "

    Protected Sub btnCancelOverwrite_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        'cancel overwrite action
        'set form back to defaults
        Me.txtUploadedFile.Visible = False
        Me.uploadFile.Visible = True
        Me.imgButtonBrowse.Visible = False
        Me.imgBeforeButtons.Visible = False
        Me.btnSave.Visible = True
        Me.btnSave.Style.Add("cursor", "default")
        Me.btnSave.ImageUrl = "~/Images/btnSaveDisabled.jpg"
        Me.lblUploadMessage.ForeColor = Drawing.Color.Black
        Me.lblUploadMessage.Text = gstrMessageText
        Me.imgBeforeMessage.ImageUrl = "~/Images/blank.gif"
    End Sub

#End Region

#Region " Folder Selections "

    Private Function SelectDestFolder() As String
        'select app dir or website root according to webconf setting
        Dim strSetRootDir As String = CStr(WebConfigurationManager.AppSettings("SetRootDirectory"))
        Dim sDestFolder As String = Server.MapPath("~/" & ViewState("Folder"))
        If strSetRootDir = "../" Then
            sDestFolder = Path.Combine(Directory.GetParent(Server.MapPath("")).FullName, ViewState("Folder"))
        End If
        Return sDestFolder
    End Function

    Private Function SelectArchiveFolder() As String
        'select app dir or website root according to webconf setting
        'will create a sub directory if path contains more than one level
        Dim strSetRootDir As String = CStr(WebConfigurationManager.AppSettings("SetRootDirectory"))
        Dim strArchiveDir As String = CStr(WebConfigurationManager.AppSettings("ArchiveDirectory"))
        If ViewState("archive") > "" Then
            'set to form request variable sent from calling form
            strArchiveDir = ViewState("archive")
        End If
        Dim sDestFolder As String = Server.MapPath("~/" & strArchiveDir)
        If strSetRootDir = "../" Then
            sDestFolder = Path.Combine(Directory.GetParent(Server.MapPath("")).FullName, strArchiveDir)
        End If
        'create the sub directory
        If Not Directory.Exists(strArchiveDir) And strArchiveDir.IndexOf("/") > -1 Then
            Try
                Directory.CreateDirectory(sDestFolder)
            Catch ex As Exception
                Me.imgBeforeMessage.ImageUrl = "~/Images/icon_caution.gif"
                Me.lblUploadMessage.ForeColor = Drawing.Color.Red
                Me.lblUploadMessage.Text = "Failed to create subfolder.  Please call support."
                'Me.lblUploadMessage.Text = ex.ToString 'unrem to test - probably permissions to directory
                Me.uploadFile.Enabled = False
                Me.uploadFile.Style.Add("cursor", "default")
                Me.btnSave.Enabled = False
                Me.btnClose.Enabled = False
                Return "error"
            End Try
        End If
        Return sDestFolder
    End Function

#End Region

#Region " Set Form Buttons "

    Protected Sub SetButtonsAfterUpload(ByVal sDestFilePathName As String)
        'set buttons and labels
        Me.lblUploadMessage.ForeColor = Drawing.Color.Green
        Me.lblUploadMessage.Text = "File uploaded.  Please click Close."
        Me.imgBeforeMessage.ImageUrl = "~/Images/blank.gif"
        Me.btnSave.Visible = True
        Me.btnSave.ImageUrl = "~/Images/btnSaveDisabled.jpg"
        Me.btnSave.Style.Add("cursor", "default")
        Me.btnSave.Enabled = False
        Me.btnClose.Enabled = True
        Me.btnClose.ImageUrl = "~/Images/btnClose.jpg"
        Me.btnClose.Style.Add("cursor", "hand")
        Me.btnCancelOverwrite.Visible = False
        Me.btnCancel.Visible = True
        Me.btnCancel.ImageUrl = "~/Images/btnCancelDisabled.jpg"
        Me.btnCancel.Style.Add("cursor", "default")
        Me.btnCancel.Enabled = False
        'assume non-IE close button if no return form value
        If Me.hReturnForm.Value > "" Then
            Me.btnClose.OnClientClick = "closeWindowNonIE();"
        End If
        'hide upload browse textbox and button and replace with fake
        ' to show file name that was uploaded
        HideUploadControl_DisplayFileName(sDestFilePathName)
    End Sub

    Protected Sub HideUploadControl_DisplayFileName(ByVal sFilePathName)
        'hide upload browse textbox and button and replace with fake
        ' to show file name that was uploaded
        'Set return value in hidden variables here
        Me.uploadFile.Visible = False
        Me.txtUploadedFile.Visible = True
        Me.txtUploadedFile.Text = ViewState("SourceFileName")
        Me.imgButtonBrowse.Visible = True
        Me.imgBeforeButtons.Visible = False
    End Sub

#End Region

#Region " Misc Functions"

    Private Function ParseDestFilePath(ByVal sFolder As String) As String
        'select app dir or website root according to webconf setting
        'setup the dest folder from form requests
        Dim strSetRootDir As String = CStr(WebConfigurationManager.AppSettings("SetRootDirectory"))
        Dim sDestFolder As String = Server.MapPath("~/" & sFolder)
        If strSetRootDir = "../" Then
            sDestFolder = Path.Combine(Directory.GetParent(Server.MapPath("")).FullName, sFolder)
        End If
        Return sDestFolder
    End Function

    Private Function ParseFileName(ByVal sFullPathName As String)
        'parse out the file name from the full path name
        Dim intExt As Integer = sFullPathName.LastIndexOf("\")
        If intExt > 0 Then
            Return sFullPathName.Substring(intExt + 1)
        End If
        Return sFullPathName
    End Function

    Private Function TimeStampFile(ByVal sFileName As String)
        'time stamp filename for archiving
        'define date time stamp
        Dim strArchiveDir As String = CStr(WebConfigurationManager.AppSettings("ArchiveDirectory"))
        Dim strDateStamp As String = DateTime.Now.ToString("yyyyMMdd") & "_" & DateTime.Now.ToString("HH:mm:ss")
        strDateStamp = strDateStamp.Replace(":", "")
        strDateStamp = strDateStamp.Replace(" ", "_")
        'parse out file extension so it can be added back to the end of the file name
        Dim intExtPos As Integer = sFileName.LastIndexOf(".")
        Dim sArchiveFileName As String = sFileName & "_" & strDateStamp
        If intExtPos > 0 Then
            Dim strExt As String = sFileName.Substring(intExtPos)
            Dim strNameOnly As String = sFileName.Substring(0, intExtPos)
            sArchiveFileName = strNameOnly & "_" & strDateStamp & strExt
        End If
        Return sArchiveFileName
    End Function

#End Region

#Region " Page Method - called from Java "

    <WebMethod()> _
Shared Function CheckFileExists(ByVal FileName As String) As Boolean
        'use web methods to check if file exists
        'called from javascript code
        If (System.IO.File.Exists(FileName)) Then
            Return True
        Else
            Return False
        End If
    End Function

#End Region

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Started programming in Business Basic in the 1980's and acquired my AS in Computer Science at that time. Promoted to IS Manager after one year of programming (sink or swim).
Self taught in SMC Basic, Visual Basic, C Shell, perl, ASP, JavaScript, vb.net, asp.net.
Now working as a Network Administrator at a hospital in Northern California.
Fell into a webmaster role when implementing the company's intranet website to support documentation.

Comments and Discussions