Link to home
Start Free TrialLog in
Avatar of M.L. Martin
M.L. MartinFlag for United States of America

asked on

Additional validation (FIle Size) on File Upload

I am performing a file upload to a folder in the root directory and writing the stored file path to SQL Server. The page and code works well. I would also like to perform additional error checking by restricting the maximum file size that can be uploaded. I have found asp.net code to do this but I am having trouble integrating the code with what I already have. I will post what I have that is working and also post the code I would like to integrate with what I have. I am not the best code writer (in any language) so I need some help getting the syntax correct. As I have tried to do this it appears that I need to combine the two routines instead of having a button click routine and a SaveAs routine but I am not sure. Thanks in advance for your help.

What I have that is working
----------------------------------------------------------------------------------------------------------------------------
Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Before attempting to save the file, verify
        ' that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then
            ' Call a helper method routine to save the file.
            SaveFile(FileUpload1.PostedFile)
        Else
            ' Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload."
        End If

    End Sub

    Sub SaveFile(ByVal file As HttpPostedFile)

        ' Specify the path to save the uploaded file to.
        Dim savePath As String = HttpContext.Current.Server.MapPath("memuploads\")

        ' Get the name of the file to upload.
        Dim fileName As String = FileUpload1.FileName

        ' Create the path and file name to check for duplicates.
        Dim pathToCheck As String = savePath + fileName

        ' Create a temporary file name to use for checking duplicates.
        Dim tempfileName As String

        ' Check to see if a file already exists with the
        ' same name as the file to upload.        
        If (System.IO.File.Exists(pathToCheck)) Then
            Dim counter As Integer = 2
            While (System.IO.File.Exists(pathToCheck))
                ' If a file with this name already exists,
                ' prefix the filename with a number.
                tempfileName = counter.ToString() + fileName
                pathToCheck = savePath + tempfileName
                counter = counter + 1
            End While

            fileName = tempfileName

            ' Notify the user that the file name was changed.
            UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" + _
                                     "Your file was saved as " + fileName

        Else

            ' Notify the user that the file was saved successfully.
            UploadStatusLabel.Text = "Your file was uploaded successfully."

        End If

        ' Append the name of the file to upload to the path.
        savePath += fileName

        ' Call the SaveAs method to save the uploaded
        ' file to the specified directory.
        FileUpload1.SaveAs(savePath)

        Dim MemUser As MembershipUser
        MemUser = Membership.GetUser()
        UserId.Value = MemUser.ProviderUserKey.ToString()

        Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("SQL2008R2_504887_golivefitnesConnectionString").ConnectionString
        Dim con As New SqlConnection(strConnString)
        Dim strQuery As String = "insert into tblFiles (UserId, savedfor, searchcode, exercisename, bodypartmg, bodypartspecific, description, FileName, FilePath) values(@UserId, @savedfor, @searchcode, @exercisename, @bodypartmg, @bodypartspecific, @description, @FileName, @FilePath)"
        Dim cmd As New SqlCommand(strQuery)
        cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = MemUser.ProviderUserKey.ToString()
        cmd.Parameters.Add("@SavedFor", SqlDbType.VarChar).Value = savedfor.Text
        cmd.Parameters.Add("@searchcode", SqlDbType.VarChar).Value = searchcode.Text
        cmd.Parameters.Add("@exercisename", SqlDbType.VarChar).Value = exercisename.Text
        cmd.Parameters.Add("@bodypartmg", SqlDbType.VarChar).Value = bodypartmg.Text
        cmd.Parameters.Add("@bodypartspecific", SqlDbType.VarChar).Value = bodypartspecific.Text
        cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = description.Text
        cmd.Parameters.AddWithValue("@FileName", fileName)
        cmd.Parameters.AddWithValue("@FilePath", "memuploads\" & fileName)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            Response.Write(ex.Message)
        Finally
            con.Close()
            con.Dispose()
        End Try

    End Sub

-----------------The code that restricts file size that I need to integrate with what I have-----------------------------
Protected Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Specify the path on the server to
        ' save the uploaded file to.
        Dim savePath As String = "c:\temp\uploads\"

        ' Before attempting to save the file, verify
        ' that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then

            ' Get the size in bytes of the file to upload.
            Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength

            ' Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
            If (fileSize < 2100000) Then

                ' Append the name of the uploaded file to the path.
                savePath += Server.HtmlEncode(FileUpload1.FileName)

                ' Call the SaveAs method to save the
                ' uploaded file to the specified path.
                ' This example does not perform all
                ' the necessary error checking.              
                ' If a file with the same name
                ' already exists in the specified path,  
                ' the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath)

                ' Notify the user that the file was uploaded successfully.
                UploadStatusLabel.Text = "Your file was uploaded successfully."

            Else
                ' Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " + _
                                         "it exceeds the 2 MB size limit."
            End If

        Else
            ' Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload."
        End If

    End Sub
ASKER CERTIFIED SOLUTION
Avatar of Bradley Fox
Bradley Fox
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of M.L. Martin

ASKER

This worked great. I couldn't figure out the correct syntax.