Sending multiple image files to mySQL - c#

How do I send multiple jpg files, as byte arrays, to my mySQL database with C#?
I have read and understand how to convert image files to byte arrays, but I can only figure out how to use that method for a single image to mySQL as a blob. My application requires the user to upload at least 2 image files and allows up to 10, while sending information from multiple textBox. I tried creating an array of byte arrays, but that didn't work. When I'd reference that array at a specific index during the INSERT string for mySQL, it seemed to store only one byte array and reference that byte array's index rather than the entire byte array that is supposed to be stored in that index. Below is some of the code showing my attempts:
///uploading the image and converting it to a byte array
private void uploadButtonClick(object sender, RoutedEventArgs e)
{
chosenFileTextBox.Text = "No file chosen";
try
{
FileStream fs = new FileStream(imageFileNameArray[i], FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageFileArray = br.ReadBytes((int)fs.Length);
///Array of byte arrays
imageArray[i] = imageFileArray;
uploadedFilesTextBox.Text += imageFileSafeNameArray[i].ToString() + "\n";
The attempt at creating the insert string is below. The string worked when I sent only one byte array, so I changed the code to attempt 2 byte array's below, with no luck:
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.Add("?_Date", MySqlDbType.VarChar).Value = dateString;
cmd.Parameters.Add("?Sex", MySqlDbType.Text).Value = sexString;
cmd.Parameters.Add("?FirstName", MySqlDbType.Text).Value =
firstNameString;
cmd.Parameters.Add("?LastName", MySqlDbType.Text).Value =
lastNameString;
cmd.Parameters.Add("?StageName", MySqlDbType.VarChar).Value =
stageNameString;
cmd.Parameters.Add("?Age", MySqlDbType.Text).Value = ageString;
cmd.Parameters.Add("?Height", MySqlDbType.VarChar).Value = heightString;
cmd.Parameters.Add("?weight", MySqlDbType.Text).Value = weightString;
cmd.Parameters.Add("?Chest", MySqlDbType.Text).Value = chestString;
cmd.Parameters.Add("?Waist", MySqlDbType.Text).Value = waistString;
cmd.Parameters.Add("?Hips", MySqlDbType.Text).Value = hipsString;
cmd.Parameters.Add("?Dress", MySqlDbType.Text).Value = dressString;
cmd.Parameters.Add("?Shirt", MySqlDbType.Text).Value = shirtString;
cmd.Parameters.Add("?Pants", MySqlDbType.VarChar).Value = pantsString;
cmd.Parameters.Add("?Shoe", MySqlDbType.VarChar).Value = shoeString;
cmd.Parameters.Add("?Email", MySqlDbType.VarChar).Value = emailString;
cmd.Parameters.Add("?Phone", MySqlDbType.VarChar).Value = phoneString;
cmd.Parameters.Add("?City", MySqlDbType.Text).Value = cityString;
cmd.Parameters.Add("?_State", MySqlDbType.Text).Value = stateString;
cmd.Parameters.Add("?Experience", MySqlDbType.VarChar).Value =
experienceString;
///"?Image1" represents Image1 column. There are 10 columns, but for
/// this example there are only 2.
cmd.Parameters.Add("?Image1", MySqlDbType.Blob).Value =
imageArray.GetValue(0);
cmd.Parameters.Add("?Image2", MySqlDbType.Blob).Value =
imageArray.GetValue(1);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
MessageBox.Show("Connection Closed");
}

You might want to look at your database structure. In this instance you probably want multiple image columns, or preferably, extract the images into a separate table so that each 'User' can have N images.
Changes might include adding an Images table with these columns:
int FK_UserID
blob Image
int ImageType
The FK_UserID is set to the userId, and you can have an ImageType column so that you can have, for example, ImageType of 1 for profile photo, etc.
Then you can do a separate insert on this table once you have stored your user and know his ID.

Related

How to show file from SqlFilestream into wpf document viewer

I am inserting docx file into an SQL table like ,
DECLARE #file AS VARBINARY(MAX)
SELECT #file = CAST(bulkcolumn AS VARBINARY(MAX))
FROM OPENROWSET(
BULK
'D:\abc.docx',
SINGLE_BLOB ) AS x
INSERT INTO ItemData(Id,fileData)
SELECT NEWID(),#file
Now file inserted into table properly.
Read File
For reading file, I am using bellow code :
"ItemNumber" is used for identity.
Everything is working fine.
But I have to show that file to the Document Viewer in WPF.
string cmdString = "Select fileData.PathName() As Path from ItemData where ItemNumber = '" + itemNumber + "' ";
SqlCommand cmd = new SqlCommand(cmdString, conn);
Object pathObj = cmd.ExecuteScalar();
if (DBNull.Value != pathObj)
filePath = (string)pathObj;
else
{
throw new System.Exception("fileData.PathName() failed to read the path name for the Chart column.");
}
this.wbControl.Navigate(filePath);
SqlTransaction transaction = conn.BeginTransaction("mainTranaction");
cmd.Transaction = transaction;
cmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
Object obj = cmd.ExecuteScalar();
byte[] txContext = (byte[])obj;
SqlFileStream sqlFileStream = new SqlFileStream(filePath, txContext, FileAccess.ReadWrite);
//byte[] buffer2 = new byte[(int)sqlFileStream.Length];
byte[] buffer = new byte[512];
int numBytes = 0;
string someData = "EKG data.";
Encoding unicode = Encoding.GetEncoding(0);
sqlFileStream.Write(unicode.GetBytes(someData.ToCharArray()), 0, someData.Length);
sqlFileStream.Seek(0L, SeekOrigin.Begin);
numBytes = sqlFileStream.Read(buffer, 0, buffer.Length);
string readData = unicode.GetString(buffer);
if (numBytes != 0)
Console.WriteLine(readData);
//Because reading and writing are finished, FILESTREAM
//must be closed. This closes the c# FileStream class,
//but does not necessarily close the the underlying
//FILESTREAM handle.
sqlFileStream.Close();
//The final step is to commit or roll back the read and write
//operations that were performed on the FILESTREAM BLOB.
cmd.Transaction.Commit();
How to I display SqlFileStream to Document Viewer in WPF?
I am storing docx file in database.

Image upload to database

So I managed to set-up a simple test page to upload and store image to my database however I am unsure of whether the storage is successful.
Whenever I store the image into my table under the column Image with the datatype Image, this is what is in the new row <Binary data>. Is this <Binary data> the image?
I was expecting it to display the image in '0' and '1' so I can compare the different items stored. But does having "" stored means that my image had been successfully stored?
My website's logic is coded in c#.
And also I had been trying to find sources with examples to how I may retrieve my image for display.
This is my current insert statement
SqlCommand com = new SqlCommand("insert into ImageTotable "
+ "(myphoto,name) values (#photo, #name)", con);
To retrieve the data will this work?
SqlCommand com2 = new SqlCommand("Select * from ImageTotable WHERE userid ='1'", con);
So if I use a datareader to store the selected items, what can I store my image to so that it will display, a label, image button, etc?
And how do I store the image into the variables? For example if I want to store text I would use:
pw = dr["password"].ToString();**
Therefore for images what would it be like?
EDIT: Full button on click event to handle the image strage
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=*;Initial Catalog=*;Integrated Security=True");
if (!FileUpload1.HasFile)
{
Label1.Visible = true;
Label1.Text = "Please Select Image File"; //checking if file uploader has no file selected
}
else
{
int length = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[length];
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
try
{
con.Open();
SqlCommand com = new SqlCommand("insert into ImageTotable "
+ "(myphoto,name) values (#photo, #name)", con);
com.Parameters.AddWithValue("#photo", pic);
com.Parameters.AddWithValue("#name", TextBox1.Text);
com.ExecuteNonQuery();
Label1.Visible = true;
Label1.Text = "Image Uploaded Sucessfully"; //after Sucessfully uploaded image
}
finally
{
con.Close();
}
}
}
First, the Image type in Db maps to Byte[] in C#, so you should convert your image into Byte[] before inserting into your database. For retrieving your image from the database, you can use the code:
MemoryStream stream = new MemoryStream(Byte[]);// you can read the image by dataadapter or datareader
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
Here is a good link: http://www.aspdotnet-suresh.com/2011/01/how-to-insert-images-into-database-and.html and hope it can help you.
here is a complete tutorials.
http://freakzmenia.blogspot.com/2010/11/image-saveretrieve-c-web-sql-server.html
http://freakzmenia.blogspot.com/2010/10/image-saveretrieve-c-windows-form-sql.html
This always helps me. 'fileupload' is the File Upload Control Name.
protected void Upload_btn(object sender, EventArgs e)
{
if (fileupload.HasFile)
{
if (fileupload.PostedFile.FileName == "")
{}
else
{
try
{
int filesize = fileupload.PostedFile.ContentLength;
if (filesize > 819200)
{Label1.Text = "File Size Should be Less than 800Kb";
}
else
{string serverFileName = Path.GetFileName(fileupload.PostedFile.FileName);
byte[] documentBinary = new byte[filesize];
fileupload.PostedFile.InputStream.Read(documentBinary, 0, filesize);
string mainquery = "";
mainquery = "insert into table(DocName,DocSize,Data,ContentType) values(#DocName,#DocSize,#Data,#ContentType)";
con.Open();
SqlCommand files_insert_cmd = new SqlCommand(mainquery,con);
files_insert_cmd.Parameters.AddWithValue("#DocName", serverFileName);
files_insert_cmd.Parameters.AddWithValue("#DocSize",fileupload.PostedFile.ContentLength);
files_insert_cmd.Parameters.AddWithValue("#Data", documentBinary);
files_insert_cmd.Parameters.AddWithValue("#ContentType",fileupload.PostedFile.ContentType);
files_insert_cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception e1)
{
Label1.Text = e1.ToString();
Label1.Visible = true;
}
}
}
}
Sorry in advance, because i am about to ask a stupid question. How are you checking data in table? are you right clicking on table and selecting edit top 200 rows
If you do like this, it will always show you as < binary Data > where as if you run sql query you can see actual characters in varbinary(max) column or Image column

How to insert BLOB datatype

I'm using the following code to insert into a blob field:
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
string SQL;
int FileSize;
byte[] rawData;
FileStream fs;
conn.ConnectionString = "server=192.168.1.104;uid=root;" +
"pwd=root;database=cady234;";
fs = new FileStream(#"d:\Untitled.gif", FileMode.Open, FileAccess.Read);
FileSize = (int)fs.Length;
rawData = new byte[FileSize];
fs.Read(rawData, 0, FileSize);
fs.Close();
conn.Open();
string strFileName = "test name";
SQL = "INSERT INTO file (file_name, file_size, file) VALUES ('" + strFileName + "', "+FileSize+", '"+rawData+"')";
cmd.Connection = conn;
cmd.CommandText = SQL;
cmd.ExecuteNonQuery();
conn.Close();
The insertion is ok but the image is not getting displayed while using "Open value in viewer":
The binary data isn't being properly passed to your insert as you are using string concatenation - you'll get rawData.ToString() which probably just prints out the TypeName (hence your binary data being 13 bytes in length compared to the filesize of > 3000 bytes); try this instead:
byte[] rawData = File.ReadAllBytes(#"d:\Untitled.gif");
FileInfo info = new FileInfo(#"d:\Untitled.gif");
int fileSize = Convert.ToInt32(info.Length);
using(MySqlConnection connection = new MySqlConnection("server=192.168.1.104;uid=root;pwd=root;database=cady234;"))
{
using(MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO file (file_name, file_size, file) VALUES (?fileName, ?fileSize, ?rawData);";
MySqlParameter fileNameParameter = new MySqlParameter("?fileName", MySqlDbType.VarChar, 256);
MySqlParameter fileSizeParameter = new MySqlParameter("?fileSize", MySqlDbType.Int32, 11);
MySqlParameter fileContentParameter = new MySqlParameter("?rawData", MySqlDbType.Blob, rawData.Length);
fileNameParameter.Value = "test name";
fileSizeParameter.Value = fileSize;
fileContentParameter.Value = rawData;
command.Parameters.Add(fileNameParameter);
command.Parameters.Add(fileSizeParameter);
command.Parameters.Add(fileContentParameter);
connection.Open();
command.ExecuteNonQuery();
}
}
I've introduced several concepts for you here; firstly, if you are going to load all of the binary data at once, simply use the static method File.ReadAllBytes - it's a lot less code.
Secondly, there is no need to use the fully qualified namespace each time - use the using directive
Thirdly, (slightly confusingly) there is a also a using statement in C#. This ensures that any object that implements IDisposable is properly cleaned up after itself. In the case of the connection, it will explicitly call Close and Dispose if you command succeeds or fails.
Finally, I've parameterized your query. Parameters are useful for many reasons; they help protect against SQL Injection, and, in this instance, they should also ensure that your data types are handled correctly. You can read more about SqlParameter (which, like, MySqlParameter is a database specific implementation but uses the same principles).
Tested as working with MySQL 5.5.15, MySQL Connector 5.2.7 running under .Net 4
How about this:
It works fine for me.
Exepte I found out that it is the wrong one for me.
<?php
// csv invoeren naar pos.
$CSV = "uitvoer.csv";
// The CSV file has only 2 colums; The "Reference" and the image name (in my case the barcode with "thumb_" in front of it.
$username = "Username";
$password = "Passwwoorrdd";
$database = "POS";
$counter = 0;
// Create connection
$conn = new mysqli("localhost", $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
//$mysqli->select_db();
ini_set('max_execution_time', 1000); //300 seconds = 5 minutes
if (($handle = fopen($CSV, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1050, ",")) !== FALSE) {
// this loops through each line of your csv, putting the values into array elements
$counter++;
$IDEE = $data[0];
// It seems that after opening the image the $data is mixed up.
$imag = "photos/".$data[1]; // where "photos/' the folder is where this php file gets executed (mostly in /var/www/ of /var/www/html/)
$fh = fopen($imag, "r");
$data = addslashes(fread($fh, filesize($imag)));
fclose($fh);
echo " Ref: ".$IDEE." ----".$counter."----<br>";
// If there will be a time-out. You could erase the part what is already done minus 1.
$sql = "UPDATE PRODUCTS SET IMAGE='".$data."' WHERE CODE=$IDEE";
// The table PRODUCTS with IMAGE. There are more data in that table. But i need only to update the IMAGE. The rest is already inserted.
if ($conn->query($sql) === TRUE) {
echo "Tabel <b>products</b> updated successfully<br>";
} else {
echo "<br>Error updating tabel <b>Products</b>: " . $conn->error;
Exit();
}
}
fclose($handle);
}
?>

How to use Microsoft Access Database's Attachment Data Type?

I'm trying to use Microsoft access database's attachment data type.
but i don't know how to use it.
I want to insert image into access database using .Net Windows Form.
In SQL Server 2008 Image data type and byte is compatibility for that.
but i don't know how to insert image into access database.
is there need to change byte like SQL Server or can directly insert into access database.
using (var connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BlankDatabase.mdb"))
{
connection.Open();
// Create table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
CREATE TABLE FileTable (
FileName VARCHAR(255),
File IMAGE)
";
command.ExecuteNonQuery();
}
var imageContent = File.ReadAllBytes(#"C:\logo.png");
// upload image to the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
INSERT INTO FileTable (FileName, File)
VALUES (#FileName, #File)
";
command.Parameters.AddWithValue("#FileName", "Logo");
command.Parameters.AddWithValue("#File", imageContent);
command.ExecuteNonQuery();
}
// retreive image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
SELECT File
FROM FileTable
WHERE FileName = 'Logo'
";
var readImageContent = (byte[])command.ExecuteScalar();
File.WriteAllBytes(#"C:\logo1.png", readImageContent);
}
// alter image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
UPDATE FileTable
SET File = #File
WHERE FileName = 'Logo'
";
command.Parameters.AddWithValue("#File", imageContent);
command.ExecuteNonQuery();
}
// delete image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
DELETE FROM FileTable
WHERE FileName = 'Logo'
";
command.ExecuteNonQuery();
}
}
In this code BlankDatabase.mdb is an empty MS Access database file.
[Edit]
When you saved image to the database, as shown above you can retrieve image bytes as shown above:
You can construct Image from image bytes like this:
var imageConverter = new ImageConverter();
pictureBox1.Image = (Image)imageConverter.ConvertFrom(fileContent);
Here is what I use to get the file attachments from an OleDB connection in .net code to a microsoft access database with attachment field types:
This method gets the file you want in Ordinal Position from the attachment field name "Pic" in my table.. you can store many files in the attachment field, so you have to specify which of the files you want.. hope this helps ( i use this as web url to take the image from the attachment field in the access database, but the COM calls will be the same in your winform app)..good luck
try
{
//You get your file in a byteArray fileType is just the ordinal file position in the fileattachment field..ex. 1, 2, 3 (shown in the access listbox)
Response.BinaryWrite(GetPicField(productID, fileType));
Response.ContentType = "image/bmp";
}
catch
{
//need to get missing product photo image here as well N/A
Response.BinaryWrite(GetNA_Image());
Response.ContentType = "image/bmp";
}
//getting from Database
private byte[] GetPicField(string productID,int fileToShow)
{
DBEngine dbe = new DBEngine();
Database db;
Recordset rs;
byte[] byteArray = null;
dbe = new DBEngine();
db = dbe.OpenDatabase(Application["DB_FileName"].ToString());
rs = db.OpenRecordset("SELECT PIC FROM PRODUCT WHERE PRODUCTID = " + productID, RecordsetTypeEnum.dbOpenForwardOnly, 0, LockTypeEnum.dbPessimistic);
if (rs.RecordCount > 0)
{
Recordset rs2 = (Recordset2)rs.Fields["Pic"].Value;
int i = 1;
while (i < fileToShow)
{
rs2.MoveNext();
i++;
}
//get the thubmnail
Field2 f2 = (Field2)rs2.Fields["FileData"]; //0 is first pic
byteArray = f2.GetChunk(20, f2.FieldSize - 20);
System.Runtime.InteropServices.Marshal.ReleaseComObject(f2);
rs2.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rs2);
f2 = null;
rs2 = null;
}
rs.Close();
db.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(dbe);
System.Runtime.InteropServices.Marshal.ReleaseComObject(db);
rs = null;
db = null;
dbe = null;
return byteArray;
}

Insert blob in oracle database with C#

I have to persist a .csv in my database, but for a more testable application I prefer don't use procedures.
Basically I just generate a file and the next instruction is put this in database.
Someone have some clue about best way to do this in code?
Here is an example to insert blob data in oracle using c# and procedures (you said prefer that means you may).
using System;
using System.Data;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.IO;
using System.Text;
//Step 1
// Connect to database
// Note: Modify User Id, Password, Data Source as per your database setup
string constr = "User Id=Scott;Password=tiger;Data Source=orcl9i";
OracleConnection con = new OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to database!");
// Step 2
// Note: Modify the Source and Destination location
// of the image as per your machine settings
String SourceLoc = "D:/Images/photo.jpg";
String DestinationLoc = "D:/Images/TestImage.jpg";
// provide read access to the file
FileStream fs = new FileStream(SourceLoc, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
// Step 3
// Create Anonymous PL/SQL block string
String block = " BEGIN " +
" INSERT INTO testblob (id, photo) VALUES (100, :1); " +
" SELECT photo into :2 from testblob WHERE id = 100; " +
" END; ";
// Set command to create Anonymous PL/SQL Block
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = con;
// Since executing an anonymous PL/SQL block, setting the command type
// as Text instead of StoredProcedure
cmd.CommandType = CommandType.Text;
// Step 4
// Setting Oracle parameters
// Bind the parameter as OracleDbType.Blob to command for inserting image
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.Blob);
param.Direction = ParameterDirection.Input;
// Assign Byte Array to Oracle Parameter
param.Value = ImageData;
// Bind the parameter as OracleDbType.Blob to command for retrieving the image
OracleParameter param2 = cmd.Parameters.Add("blobfromdb", OracleDbType.Blob);
param2.Direction = ParameterDirection.Output;
// Step 5
// Execute the Anonymous PL/SQL Block
// The anonymous PL/SQL block inserts the image to the
// database and then retrieves the images as an output parameter
cmd.ExecuteNonQuery();
Console.WriteLine("Image file inserted to database from " + SourceLoc);
// Step 6
// Save the retrieved image to the DestinationLoc in the file system
// Create a byte array
byte[] byteData = new byte[0];
// fetch the value of Oracle parameter into the byte array
byteData = (byte[])((OracleBlob)(cmd.Parameters[1].Value)).Value;
// get the length of the byte array
int ArraySize = new int();
ArraySize = byteData.GetUpperBound(0);
// Write the Blob data fetched from database to the filesystem at the
// destination location
FileStream fs1 = new FileStream(#DestinationLoc,
FileMode.OpenOrCreate, FileAccess.Write);
fs1.Write(byteData, 0,ArraySize);
fs1.Close();
Console.WriteLine("Image saved to " + DestinationLoc + " successfully !");
Console.WriteLine("");
Console.WriteLine("***********************************************************");
Console.WriteLine("Before running this application again, execute 'Listing 1' ");
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] blob = ReadFile(txtPath.Text);
//Initialize Oracle Server Connection
con = new OracleConnection(conString);
//Set insert query
string qry = "insert into Imgpn (imgpath,photo) values('" + txtPath.Text + "'," + " :BlobParameter )";
OracleParameter blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = "BlobParameter";
blobParameter.Value = blob;
//Initialize OracleCommand object for insert.
cmd = new OracleCommand(qry, con);
//We are passing Name and Blob byte data as Oracle parameters.
cmd.Parameters.Add(blobParameter);
//Open connection and execute insert query.
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Image added to blob field");
GetImagesFromDatabase();
cmd.Dispose();
con.Close();
//this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
void GetImagesFromDatabase()
{
try
{
//Initialize Oracle connection.
con = new OracleConnection(conString);
//MessageBox.Show("Connection Successfull");
//Initialize Oracle adapter.
OracleDataAdapter oda = new OracleDataAdapter("Select * from Imgpn", con);
//Initialize Dataset.
DataSet DS = new DataSet();
//Fill dataset with ImagesStore table.
oda.Fill(DS, "Imgpn");
//Fill Grid with dataset.
dataGridView1.DataSource = DS.Tables["Imgpn"];
//
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
here is the simple way to insert image into oracle database ane retrieve ane show in datagridview

Categories