Solved

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

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

Network it in WD Red

There's an industry-leading WD Red drive for every compatible NAS system to help fulfill your data storage needs. With drives up to 8TB, WD Red offers a wide array of solutions for customers looking to build the biggest, best-performing NAS storage solution.  

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Error in page 3 44
Word Directory is not in the drop down list 4 24
Runtime Exceptions when trying to submit data 28 36
Migrate Application To New Mac 5 29
Foreword (May 2015) This web page has appeared at Google.  It's definitely worth considering! https://www.google.com/about/careers/students/guide-to-technical-development.html How to Know You are Making a Difference at EE In August, 2013, one …
These days, all we hear about hacktivists took down so and so websites and retrieved thousands of user’s data. One of the techniques to get unauthorized access to database is by performing SQL injection. This article is quite lengthy which gives bas…
Learn how to set-up custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.
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.

914 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

12 Experts available now in Live!

Get 1:1 Help Now