SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read() == true)
{
lblHead.Text = sdr["HEADING"].ToString();
lblData.Text = sdr["COMMENT"].ToString();
}
conn.Close();
That is the code for normal data value retrieve from table now I want to get picture from SQL Server that is saved as Binary data that code mention in bottom. So I want to retrieve picture into an Image control of asp.net; please guide me.
if (FileUpload1.HasFile)
{
conn.Close();
String SqlQery;
SqlQery = "select max(CMTID) from FTAB";
SqlCommand cmdid = new SqlCommand(SqlQery, conn);
conn.Open();
MaxID = (int)(cmdid.ExecuteScalar()) + 1;
conn.Close();
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimg = FileUpload1.PostedFile;
myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (#imgid, #image, #comment, #datetm, #heading)", conn);
SqlParameter imgid = new SqlParameter("#imgid",SqlDbType.Int);
imgid.Value = MaxID;
cmd.Parameters.Add(imgid);
SqlParameter uploading = new SqlParameter("#image", SqlDbType.Image);
uploading.Value = img;
cmd.Parameters.Add(uploading);
SqlParameter cmtt = new SqlParameter("#comment", SqlDbType.NVarChar);
cmtt.Value = RadTextBox3.Text;
cmd.Parameters.Add(cmtt);
SqlParameter dttm = new SqlParameter("#datetm", SqlDbType.DateTime);
dttm.Value = DateTime.Now;
cmd.Parameters.Add(dttm);
SqlParameter hhding = new SqlParameter("#heading", SqlDbType.NVarChar);
hhding.Value = RadTextBox8.Text;
cmd.Parameters.Add(hhding);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lblHead.Text = "Image uploaded";
}
else
{
lblHead.Text = "No file selected";
}
Try this
SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
img.ImageUrl = filePath;
But I would say this isn't the best way to do it, you should save your uploaded images as files as in your website and save the path of that file in your database.
yogi's answer is correct in principle, but requires a web server directory "temp" and write access on an IIS directory.
You can also solve the problem using an image handler as explained in another SO question. Database retrieval is done in the same way, but the rendering happens from a stream, rather than a temp file.
Related
I have sqlite database who store Arabic text in varchar field
I used this code,but when try to read the value question mark is appear instead character
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt FROM tblQTxt'", con);
con.Open();
SQLiteDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr["Qtxt"].ToString();
dr.Close();
con.Close();
I used "DB Browser for SQLite" fro opening database
when try to view field as binary mode and then export as text I will see the true character
how can read this filed truly?
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt2 FROM tblQTxt where Sore='1' and Aye='1'", con);
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
if (dSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dSet.Tables[0].Rows[0]["Qtxt2"]);
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
StreamReader reader = new StreamReader(ms,Encoding.GetEncoding(1256));
string text = reader.ReadToEnd();
textBox1.Text = text;
}
public void ProcessRequest(HttpContext context)
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString.ToString());
// Create SQL Command
int adid= int.Parse(context.Request.QueryString["adid"]);
int imgid = int.Parse(context.Request.QueryString["imgid"]);
MySqlCommand cmd = new MySqlCommand();
//cmd.CommandText = "Select i.image_id, i.image_name, i.image_byteImage, i.image_adId from images i,postadverties p where i.image_adId =#ID";
cmd.CommandText = "SELECT image_id,image_byteImage FROM images WHERE image_adId="+ adid + " and image_id="+ imgid;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
//MySqlParameter AdId = new MySqlParameter("#ID", MySqlDbType.Int32);
//MySqlParameter imgid = new MySqlParameter("#imgid", MySqlDbType.Int32);
//AdId.Value =
//imgid.Value =
//cmd.Parameters.Add(AdId);
//cmd.Parameters.Add(imgid);
con.Open();
MySqlDataReader dReader = cmd.ExecuteReader();
if (dReader.Read())
{
byte[] binaryimg = (byte[])dReader["image_byteImage"];
string base64string = "data:image/jpeg;base64," + Convert.ToBase64String(binaryimg);
context.Response.Write(base64string);
context.Response.Flush();
context.Response.End();
}
dReader.Close();
con.Close();
}
Click here to see result
When trying to display images stored in database above result is displayed instead of image.No clue why this issue is coming.Is there any problem while converting it or some else.In another page it works and on some pages it does not.
I'm developing an admin panel and a web service but how to add an image data into SQL Server database and retrieve it in admin panel in GridView? Everything adds fine, shows fine except the images. I'm using HTML Input (file) control. No errors just image is not displaying but lblTest shows accordingly.
And how to make my Button can ADD and Refresh so user can see the new data instantly.
Thank you!
Here is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
showSplash();
}
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
Int32 fileLength = 0;
protected void ButtonTest_Click(object sender, EventArgs e)
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\icon\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine with no file";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
My other related question links:
Ajax tabContainer:
I am trying to save images in a SQL Server database.
I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.
I tried a lot but didn't find a solution.
Here is the code (convert bytes to Image)
if (fImage.HasFile)
{
if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
{
int filelenght = fImage.PostedFile.ContentLength;
byte[] imagebytes = new byte[filelenght];
fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into tbImage(Img) values(#img)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#img", imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Image saved to database");
}
}
Something like this will convert Byte[] to Image:
MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
byte[] img = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(img);
PictureBox1.Image = Image.FromStream(ms);
}
}
con.Close();
All you need to do is to store the byte content in a variable and then write it to the File system:
var imgBlob = ... // Load the image binary array from the database
File.WriteAllBytes("path/to/file.jpg", imgBlob);
you can create a controller action to handle retrieving the image
public FileResult DownloadImage(int Photo_Id)
{
byte[] fileBytes = "get bytes from db here";
string fileName = "file name here"
return File(fileBytes, "contentType of the image" , fileName);
}
Thanks for your valuable reply.
i solve this problem with this one.
give a look.
int id = Convert.ToInt32(drpImage.SelectedValue);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id+"", con);
con.Open();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
byte[] img = (byte[])dr["img"];
string base64string = Convert.ToBase64String(img, 0, img.Length);
lblImage.Text += "<img src='data:image/png;base64," + base64string + "' alt='No Image' width='200px' vspace='5px' hspace='5px' />";
}
}
con.Close();
I am working on oracle 11g. I created a table which have 3 columns, SQL for create table is
create table blobvideo(fileid int,filename varchar2(100), filedata blob);
My code to insert video in that table is
FileInfo fi = new FileInfo("C:\videoPath.mp4");
FileStream fs = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
byte[] fileToByte = new byte[fs.Length];
fs.Read(fileToByte, 0, Convert.ToInt32(fs.Length));
String strSQL = "INSERT INTO blobvideo (FileId,filename,FILEDATA) VALUES (1,'" + fi.FullName + "',:TEXT_DATA)";
OracleParameter parmData = new OracleParameter();
parmData.Direction = ParameterDirection.Input;
parmData.OracleDbType = OracleDbType.Blob;
parmData.ParameterName = "TEXT_DATA";
parmData.Value = fileToByte;
OracleCommand cm = new OracleCommand();
cm.Connection = myConnection;
cm.Parameters.Add(parmData);
cm.CommandText = strSQL;
myConnection.Open();
cm.ExecuteNonQuery();
myConnection.Close();
My code to get BLOB is
OracleCommand ocmd1 = new OracleCommand("select * from blobfile ", myConnection);
myConnection.Open();
OracleDataReader rds = ocmd.ExecuteReader();
rds.Read();
OracleBlob newBlob = rds.GetOracleBlob(2);
Insertion is working well, but my question is how can i get that video and how can i play that video in windows media player or vlc or any other video player that works with C#.