Solved

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

Posted on 2014-07-21
3
1,753 Views
Last Modified: 2014-08-25
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

0
Comment
Question by:derrekdeveloper
3 Comments
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 40210200
- Question moved from Classic ASP to ASP.NET

- Code snippet placed in a code box

padas
Topic Advisor
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 40216828
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
 

Author Closing Comment

by:derrekdeveloper
ID: 40284375
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

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

If I have to fix slow responding website my first thoughts are server side optimizations: the database may not be optimized or caching is not enabled, or things like that. We often overlook another major part of our web application: the client. We o…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question