Solved

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

Posted on 2014-07-21
3
1,722 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Thoughout my experience working on eCommerce web applications I have seen applications succumbing to increased user demand and throughput. With increased loads the response times started to spike, which leads to user frustration and lost sales. I ha…
It’s a strangely common occurrence that when you send someone their login details for a system, they can’t get in. This article will help you understand why it happens, and what you can do about it.
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…
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.

708 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now