Hi
I have the following code that uploads images and other files to an SQL Server DB on GoDaddy via a FileUpload Control on an aspx page.
Public Function InsertData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpload.Click
' Read the file and convert it to a Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype variable value based on the File Extension
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
'insert the file into database
Dim strQuery As String = "insert into tblImg" _
& "(Name, ContentType, Data)" _
& " values (@Name, @ContentType, @Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype
cmd.Parameters.Add("@Data", SqlDbType.VarBinary).Value = bytes
InsertData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." _
& " Upload Image/Word/PDF/Excel formats"
End If
End Sub
The DB table on GoDaddy is called tblImg and is made up of the following fields:
Id - int - Primary key autoincrement Id.Incr=1 Id.seed=1
Name - varchar
ContentType - varchar
Data - varbinary MAX
My problem is that every time I run the code I get two records inserted the first one is correct containing the text and the image the second record contains the text again and no image. I only need one record added not two. Any help will be highly appreciated thanks.