Insert & Retrieve Image in Postgresql database form VBNet - vb.net

I want to insert and retrieve image in Postgresql database from VB.net on button click event. My table has one column "image" with datatype bytea. I have written below code but not getting desired output:
'Insert
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
Dim image1 As Byte()
Dim FS As FileStream = New FileStream("C:\0.jpg", FileMode.Open, FileAccess.Read)
Dim BR As BinaryReader = New BinaryReader(FS)
Dim lg As Long = FS.Length
Dim length As Integer = Convert.ToInt32(lg)
image1 = BR.ReadBytes(length)
conn.Open()
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(#image1)", conn)
'Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table1 values('" & timestamp & "','" & serialno & "','" & modelname & "','0','0','0','0','0','0','0','0','0','0','0','0')", conn)
Command.Parameters.Add(New NpgsqlParameter("#image1", NpgsqlTypes.NpgsqlDbType.Bytea))
Command.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'retrieve
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Try
conn.Open()
Dim com As NpgsqlCommand = New NpgsqlCommand("select image from table2", conn)
Dim reader As NpgsqlDataReader = com.ExecuteReader()
Dim imageInBytes As Byte() = reader("image")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("E:\image")
PictureBox6.Image = image
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

You need values in parameters in 'Insert'...Change this...
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(#image1)", conn)
Command.Parameters.Add(New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea))
For this...
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(:image1)", conn)
Dim param As NpgsqlParameter = New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea)
param.Value = image1
Command.Parameters.Add(param)
And in 'Retrieve' you need take length before... Change this...
Dim imageInBytes As Byte() = reader("image")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("E:\image")
PictureBox6.Image = image
For something similar to this...
Dim imageInBytes As Byte()
reader.Read()
' Retrieve the length of the necessary byte array.
Dim column as integer = reader.GetOrdinal("name_column")
Dim len As Long = reader.GetBytes(column, 0, Nothing, 0, 0)
' Create a buffer to hold the bytes, and then
' read the bytes from DataReader.
ReDim imageInBytes(CInt(len))
reader.GetBytes(column, 0, imageInBytes, 0, CInt(len))
PictureBox1.Image = New Bitmap(New MemoryStream(imageInBytes))

Related

Import and Export csv File from DataGridView

High there, I'm currently making a small piece of software for a college project, The goal of the project is for the user to import ingredients and infomration and then they can create meals with these ingredients.
I'm having an issue though where when I load my csv file in after I've used the software once to add in a new ingredient I get the error: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" and it highlights the section of the code "newRow("Protien") = columns(1)" Now I think is because when it loads in the data from the recently saved csv file it has a row at the top that is filled with the headers, is there any way that I can save the csv file without including the headers from the data table?
Code that laods in the csv file:
'Sets up the data table that will be used to store the ingredients and their information.'
With ingredientTable
.Columns.Add("Name", System.Type.GetType("System.String"))
.Columns.Add("Protien", System.Type.GetType("System.Decimal"))
.Columns.Add("Fat", System.Type.GetType("System.Decimal"))
.Columns.Add("Salt", System.Type.GetType("System.Decimal"))
.Columns.Add("Carbs", System.Type.GetType("System.Decimal"))
.Columns.Add("Calories", System.Type.GetType("System.Decimal"))
End With
'Loads in the information from the CSV file to display all the previouly saved ingredients'
Dim fileReader As New IO.StreamReader("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", System.Text.Encoding.Default)
Dim ingredientString As String = ""
Do
ingredientString = fileReader.ReadLine
If ingredientString Is Nothing Then Exit Do
'Reads what is on the CSV file and sets up the columns and the rows.'
Dim columns() As String = ingredientString.Split(",")
Dim newRow As DataRow = ingredientTable.NewRow
newRow("Name") = columns(0)
newRow("Protien") = columns(1)
newRow("Fat") = columns(2)
newRow("Salt") = columns(3)
newRow("Carbs") = columns(4)
newRow("Calories") = columns(5)
ingredientTable.Rows.Add(newRow)
Loop
fileReader.Close()
DataGridView1.DataSource = ingredientTable
Me.Text = ingredientTable.Rows.Count & "rows"
Code that saves the CSV file:
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
#Region "Save ingredients"
Dim csvFile As String = String.Empty
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
'Used to ge the rows
For Each row As DataGridViewRow In DataGridView1.Rows
'Used to get each cell in the row
For Each cell As DataGridViewCell In row.Cells
csvFile = csvFile & cell.FormattedValue & ","
Next
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", csvFile, False)
#End Region
Here are a few options to consider, for loading data from a CSV to a DGV.
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
End Class
You must try this code.
OpenButton
Dim OpenFileDialog1 As New OpenFileDialog()
Dim constr As String
Dim con As OleDb.OleDbConnection
Try
OpenFileDialog1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm;"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.txtOpen.Text = OpenFileDialog1.FileName
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDb.OleDbConnection(constr)
con.Open()
cboSheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
cboSheet.DisplayMember = "TABLE_NAME"
cboSheet.ValueMember = "TABLE_NAME"
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Load Button
Dim constr As String
Dim dt As DataTable
Dim con As OleDbConnection
Dim sda As OleDbDataAdapter
Dim row As DataRow
Try
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDbConnection(constr)
sda = New OleDbDataAdapter("Select * from [" + cboSheet.SelectedValue + "]", con)
dt = New DataTable
sda.Fill(dt)
For Each row In dt.Rows
DataGridView3.DataSource = dt
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I hope it will works! :)

Error when updating image in ms access

When I update the image in ms access i get this error:
coulddn't find d/bin/debug/openfilediloge1
and when I choose another image I get
couldn't save currently lockedby another user
my code as follow.
Private Sub Btnedit_Click(sender As Object, e As EventArgs) Handles Btnedit.Click
'Dim d As New DAL
'd.Dataedit("delete from labdetails")
'Pic.Image = Nothing
'MsgBox("من فضلك اختر صورة")
' btnsave_Click(Nothing, Nothing)
Try
Dim fsreader As New FileStream(dlgpics.FileName, FileMode.Open, FileAccess.Read)
Dim breader As New BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
Dim strsql As String
Dim acscmd As New OleDbCommand
Dim con As New OleDbConnection
con = New OleDbConnection(("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath() & "\lab2015.accdb;Jet OLEDB:Database Password=mak;"))
strsql = "update labdetails set labnme=#labnme,labspecial=#labspecial,labadress=#labadress,labphone=#labphone,labtime=#labtime,lablogo=#lablogo,labprint=#labprint,labnameenglish=#labnameenglish,labspecialenglish=#labspecialenglish"
acscmd.CommandText = strsql
acscmd.Connection = con
acscmd.Parameters.AddWithValue("#labnme", txtlabname.Text)
acscmd.Parameters.AddWithValue("#labspecial", txtspeciality.Text)
acscmd.Parameters.AddWithValue("#labadress", txtadress.Text)
acscmd.Parameters.AddWithValue("#labphone", txtphone.Text)
acscmd.Parameters.AddWithValue("#labtime", txttime.Text)
acscmd.Parameters.AddWithValue("#lablogo", imgbuffer)
' If printchck.Checked = True Then
acscmd.Parameters.AddWithValue("#labprint", printchck.Checked)
acscmd.Parameters.AddWithValue("#labnameenglish", Txtlab.Text)
acscmd.Parameters.AddWithValue("#labspecialenglish", txtspecial.Text)
' Else
' acscmd.Parameters.AddWithValue("#labprint", "No")
' End If
con.Open()
acscmd.ExecuteNonQuery()
acscmd.Dispose()
Me.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
labdetails_Load(Nothing, Nothing)
End Sub

Loading image from database to picturebox

I'm new to visual basic and I have a problem in loading the image from my database. I'm currently using image data type. This is how I save the image
Imports System.Data
Imports System.Data.SqlClient
Public Class ScannerX_Add
Dim ImageFilename As String
Dim ImageUpload As Image
Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Scan.Click
Try
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:\Users\ITTestServer\Desktop\Dekstop\"
OpenFileDialog1.ShowDialog()
ScannerX_Pic.Image = Image.FromFile(OpenFileDialog1.FileName)
ImageFilename = OpenFileDialog1.FileName
ImageUpload = Image.FromFile(OpenFileDialog1.FileName)
Catch ex As Exception
MsgBox("Please insert scan finger")
Exit Sub
End Try
End Sub
Private Sub Btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Save.Click
If ImageFilename <> "" Then
Dim imageNameTemp As String
imageNameTemp = ImageFilename
While (imageNameTemp.Contains("\"))
imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
End While
Dim ms As New IO.MemoryStream
If ImageFilename.Contains("jpeg") Or ImageFilename.Contains("jpg") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If ImageFilename.Contains("png") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If ImageFilename.Contains("gif") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If ImageFilename.Contains("bmp") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
Dim b() As Byte = ms.ToArray()
Dim cmd As New SqlCommand("Insert into Scanner (Name,Finger) VALUES('" & TxtBox_Name.Text.Trim & "','" & imageNameTemp & "')", Connection)
cmd.Parameters.Add("#BLOBData", SqlDbType.Image, b.Length).Value = b
cmd.ExecuteNonQuery()
MsgBox("Profile Has Been Saved")
Me.Close()
End If
End Sub
Now I need to load my image to picturebox which is currently in the Main form.
Private Sub ButtonX1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX1.Click
Command.CommandText = ("select Finger FROM Scanner")
Command.Connection = Connection
Dim da As New SqlDataAdapter(Command)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
Dim bytBLOBData() As Byte = _
ds.Tables(0).Rows(c - 1)("imagedate")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
ScannerX_Pic2.Image = Image.FromStream(stmBLOBData)
End If
End Sub
Now I get the error Object reference not set to an instance of an object.
To save an image you could do something like this
Dim sql As String = "INSERT INTO Information VALUES(#name,#photo)"
Image Img = PictureBox1.BackgroundImage
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
Img.Save(ms, Img.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
And to retrieve an image
cmd = New SqlCommand("select photo from Information where name='Rose'", con)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
Also check out this article it's doing exactly what you are trying to achieve
http://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database
The sql is selecting a column named "Finger":
"select Finger FROM Scanner"
But it's later trying to build an Image object from a column named "imagedate":
ds.Tables(0).Rows(c - 1)("imagedate")
It needs to use the same column name as the SQL result set:
ds.Tables(0).Rows(c - 1)("Finger")
There may be other problems as well, but that's what jumped out at me right away.

How to Display/Get Image from Access Database to PictureBox in VB [duplicate]

This question already has an answer here:
How to Show/Retrieve or Get the Image to PictureBox from Access Database?
(1 answer)
Closed 5 years ago.
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
GetPicture()
End Sub
Public Sub GetPicture()
con.Open()
Dim dt As New DataTable("Users")
Dim rs As New OleDb.OleDbDataAdapter("Select * from Users where StudentNumber='" & TextBox1.Text & "' ", con)
rs.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Refresh()
Label1.Text = dt.Rows.Count
rs.Dispose()
con.Close()
If Val(Label1.Text) = 1 Then
Dim i As Integer
i = DataGridView1.CurrentRow.Index
PictureBox1.Image = FixNull(DataGridView1.Item(6, i).Value)
End If
______________________________
I got this Error on the line: PictureBox1.Image = FixNull(DataGridView1.Item(6, i).Value)
-> Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.
Screenshot:
I just figgured it out, this is the solution
Public Class Form
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\UsersDB.accdb")
Dim cmd As New OleDbCommand("", con)
Dim Reader As OleDb.OleDbDataReader
Dim cn As New OleDbConnection
Dim i As Integer
Public Sub GetData()
con.Open()
Dim dt As New DataTable("Users")
Dim rs As New OleDb.OleDbDataAdapter("Select * from Users where StudentNumber='" & TextBox1.Text & "' ", con)
rs.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Refresh()
Label1.Text = dt.Rows.Count
rs.Dispose()
con.Close()
If Val(Label1.Text) = 1 Then
Dim i As Integer
i = DataGridView1.CurrentRow.Index
'Image
Dim bytes As [Byte]() = (DataGridView1.Item(6, i).Value)
Dim ms As New MemoryStream(bytes)
PictureBox1.Image = Image.FromStream(ms)
End If
End Sub
End Class

Image upload to and download from SQL using VB.Net + Image downloads incorrectly

Imports System
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Read the file and convert it to 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 based on File Extension
Select Case ext
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
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(fs.Length)
lblMessage.Text = bytes.ToString 'System.Text.Encoding.Unicode.GetString(bytes)
'insert the file into database
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Try
con.Open()
Dim strQuery As String = "insert into uploadedImages (Name, ContentType, Data) values ('" & filename & "','" & contenttype & "','"
Dim bytesLength As Integer = bytes.Length - 1
For i As Integer = 0 To bytesLength
strQuery = strQuery & bytes(i)
Next
strQuery = strQuery & "')"
Dim cmd As New SqlCommand(strQuery)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
con.Dispose()
End Try
' InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully" '& System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." & " Upload Image JPG or PNG formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").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
' code to retrieve image
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes As String = CType(dt.Rows(0)("Data"), String)
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
' convert a string to a byte array
Dim encoding As New System.Text.UTF8Encoding()
Response.BinaryWrite(encoding.GetBytes(dt.Rows(0)("Data")))
Response.Flush()
Response.End()
End Sub
Protected Sub btn_download_Click(sender As Object, e As EventArgs) Handles btn_download.Click
Dim strQuery As String = "select Name, ContentType, Data from uploadedImages where id=12"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("12", SqlDbType.Int).Value = 1
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
End Class
The image downloads but the file is corrupted , I think the problem is when retrieving the string from the database and turning it into bytes ... Appreciate any help