ASP.Net File Upload - Save image path to database table

I am trying to make the following code work but I have two major problems.
1. I don't want to use an absolute path like I have displayed.
"C:\inetpub\wwwroot\empty\memuploads"

My service provider will not allow access to a directory like that. How do I change the code so that I can use something like "memuploads" with memuploads being in the inetpub/wwwroot directory? I think I can do something like this but I'm not sure. Dim saveDir As String = "\Uploads\"

2. The code saves to C:\inetpub\wwwroot\empty\memuploads without any problems but I am also trying to save the image or saved file path to a SQLServer database table. I have some code below with a connection string but I am certain I am not doing this correctly. I do feel that I am close to making this work but I do need some help on changing the absolute saved path and writing the path to the SQL table. I am attempting to use this solution because the code prevents the user from creating a duplicate name situation and/or overwriting and existing file.

Imports System.Data.SqlClient
Imports System.Data

Partial Class filepath
    Inherits System.Web.UI.Page

    Sub UploadButton_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 = "C:\inetpub\wwwroot\empty\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)

    End Sub



    Private Function GetConnectionString() As String


        'sets the connection string from your web config file. "DBConnection" is the name of your Connection String

        Return System.Configuration.ConfigurationManager.ConnectionStrings("SQL2008R2_504887_golivefitnesConnectionString").ConnectionString

    End Function



    Private Sub ExecuteInsert(name As String, size As Integer, path As String)




        Dim conn As New SqlConnection(GetConnectionString())


        Dim sql As String = "INSERT INTO tblFiles (ImageName, ImageSize, ImagePath) VALUES " + " (@ImgName,@ImgSize,@ImgPath)"

        Try




            conn.Open()

            Dim cmd As New SqlCommand(sql, conn)

            Dim param As SqlParameter() = New SqlParameter(2) {}



            param(0) = New SqlParameter("@ImgName", SqlDbType.NVarChar, 50)

            param(1) = New SqlParameter("@ImgSize", SqlDbType.BigInt, 9999)

            param(2) = New SqlParameter("@ImgPath", SqlDbType.VarChar, 50)



            param(0).Value = name

            param(1).Value = size

            param(2).Value = path



            For i As Integer = 0 To param.Length - 1



                cmd.Parameters.Add(param(i))
            Next



            cmd.CommandType = CommandType.Text


            cmd.ExecuteNonQuery()

        Catch ex As System.Data.SqlClient.SqlException


            Dim msg As String = "Insert Error:"

            msg += ex.Message


            Throw New Exception(msg)
        Finally




            conn.Close()
        End Try

    End Sub



    

End Class

Open in new window

derrekdeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
- Question moved from Classic ASP to ASP.NET

- Code snippet placed in a code box

padas
Topic Advisor
0
Robert SchuttSoftware EngineerCommented:
1. You can use Server.MapPath() to convert a relative path to an absolute path for the server that the code is running on.

* It is better to use Path.Combine() instead of + for folders and filenames as a missing slash or backslash makes it use the wrong location.

2. Your database code works fine! I included a call to it below (amongst other changes):
    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 = System.IO.Path.Combine(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 = System.IO.Path.Combine(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

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

        ExecuteInsert(fileName, FileUpload1.PostedFile.ContentLength, savePath)

    End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
derrekdeveloperAuthor Commented:
This is exactly what I was looking for. Thanks Robert. Your solution allows me to do exactly as required by the business requirement. THANKS AGAIN.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Frameworks

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.