How to display Image using repeater - c#

I have a page to upload a photo into my database. Then when I click upload, the photo has been saved as binary format in database:
protected void Button1_Click(object sender, EventArgs e)
{
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "','" + bytes + "')", con);
con.Open();
cmd.ExecuteNonQuery();
When I am trying to retrieve image then it is not displayed, how to display image using repeater?
Database: menu image
<asp:Image ID="ViewPhotoImage" runat="server" ImageUrl='<%# GetImage(Eval("menu")) %>' Height="190px" Width="180px"/>
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[]) img);
}

I think your problem may be in how you are putting the data into the database. You may not have valid image data in the database at all. Does that code run for you when you upload an image? When I run it it errors out on the sql command because when you implicitly convert a byte[] into a string in c# you get "System.Byte[]" instead of the string representation of the data. You need to convert that byte[] into a binary string. That link has a bunch of ways to do it, and here's your upload code with one of those ways (Not Recommended, see below):
(Edited, see comment below)
Byte[] bytes = null;
string hex = "0";
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
hex = "0x" + BitConverter.ToString(bytes).Replace("-", "");
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "'," + hex + ")", con);
con.Open();
cmd.ExecuteNonQuery();
You also might want to move that sql code into the if block, but maybe that's what you want, just thought i'd mention it in case.
HOWEVER...
I would be remiss if I did not strongly suggest that you parameterize your sql statement to avoid injection attacks. But not only is it better for security, it makes working with the binary data much easier as there is no need to string convert. Here's the relevant code with parameters:
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES(#disc, #menu)", con);
cmd.Parameters.AddWithValue("#disc", TextBox.Text);
cmd.Parameters.AddWithValue("#menu", bytes);
con.Open();
cmd.ExecuteNonQuery();
Once I did that, your other code worked fine and I was able to see my test images in the repeater. I hope that helps!

Related

Opening the varbinary column in a popup window using contenttype

I am making a file uploader using html tags. I have id, Name and Data in my table. Data is storing the contents of the file in binary format in a column of datatype varbinary(max). I am able to successfully upload the file and I am also able to read the byte array back.
Code for upload at code behind:
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into FileUploader2 values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Context.Response.Write("Uploaded Successfully!");
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
I am also creating a grid which shows me list of files along with an icon which when clicked will view me the file after reading the byte array. I have a JS function on that onclick which I am accessing through WebMethod at code-behind. Following is my code when user clicks on view icon:
[System.Web.Services.WebMethod]
public static void ShowDocument()
{
string filename = string.Empty;
string contentType = string.Empty;
byte[] bytes = null;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
filename = (string)reader["Name"];
contentType = (string)reader["ContentType"];
bytes = (byte[])reader["Data"];
}
}
}
}
System.Web.HttpContext.Current.Response.ContentType = contentType;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + filename);
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
System.Web.HttpContext.Current.Response.Flush();
}
This code is working fine as well and correctly reads all the columns. Now after reading, I want to view the file as well in a pop window. How can I do so? I think I have to take contenttype to let it know what type of file I want to open and then use the bytes to do so. But I have no idea how to achieve that.

Store a File Size in a database table using file upload controle

I need to save a file size in database table while uploading a file in using upload control.
i am simple pitching my upload control code here.
Please take a look.
protected void UploadFileControl(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
using (SqlConnection con = new SqlConnection(con))
{
string str = "INSERT INTO XYZ VALUES (#FileName, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(str))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", fileName);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
This is simple upload control code.

ORA-01460: unimplemented or unreasonable conversion requested-uploading files

Following is the code to upload file in party_images table.
protected void upload_Click(object sender, EventArgs e)
{
try
{
using (OracleConnection connection = new OracleConnection(conString))
{
connection.Open();
string filename = Path.GetFileName(FileUpload1.FileName);
string[] tokenize = filename.Split('.');
FileUpload1.SaveAs(Server.MapPath("~/files/") + descBox.Text + "." + tokenize[1]);
string sourceLoc = Server.MapPath("~/files/" + descBox.Text + "." + tokenize[1]);
FileStream fs = new FileStream(sourceLoc, FileMode.Open, FileAccess.Read);
byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
String block = " BEGIN " +
" INSERT INTO party_images(party_id, sr_no, descr, party_image) VALUES ('"+Session["userId"]+"',"+srNo.Text+",'"+descBox.Text+"."+tokenize[1]+"', :1); " +
" END; ";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.LongRaw);
param.Direction = ParameterDirection.Input;
param.Value = ImageData;
cmd.ExecuteNonQuery();
descBox.Text = "";
srNo.Text = "";
}
}
catch (Exception ex) {
ClientScript.RegisterStartupScript(this.GetType(), "unSuccessMessage", "window.onload = function(){ alert('"+ex.Message+"')};", true);
}
finally
{
populateGrid(loadFromDb());
}
}
table description is,
PARTY_ID is VARCHAR2(10)
SR_NO is NUMBER
DESCR is VARCHAR2(50)
PARTY_IMAGE is LONG RAW()
This function is uploading all the files i.e., images,.docx,.pdf,.sql but when I upload any .docx containing screen shots or pictures then the upper error appears.
I have tried the following links,
ORA-01460: unimplemented or unreasonable conversion requested
The requested format conversion is not supported.
ORA-01460: unimplemented or unreasonable conversion requested
But I haven't got any solution. How can I upload any type of file without having this error?
Why are you using LONG RAW to store binary objects? That's a datatype which has been deprecated for over twenty years.
If you define PARTY_IMAGE as a BLOB (or maybe BFILE) you will find it a lot easier to work with. Find out more.

Why I am getting one more character?

Hello Im using this C# code for images upload.
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Content", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
I upload the image in a longblob field, then to show the image I am using C# WebService, AJAX, JavaScript, converting the image to Base64String but image is displayed like if do not exist.
Here is my Base64String:
Base64String
As you can see the problem is with this extra characters:
AAEAAAD/////AQAAAAAAAAAPAQAAAHgBAAAC
Why this happen? And how can I solve it?
can you replace the bellowed lines with your above code
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
System.Drawing.Image imagetuUpload = System.Drawing.Image.FromStream(fs);
Bitmap bitmap = new Bitmap(imagetuUpload);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] upproimag = new byte[stream.Length + 1];
stream.Read(upproimag, 0, upproimag.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Content", upproimag);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
i hop it may help you :)
long time back i was in same issue i do not remember other than doing this at that time:
I check if I am wrong or not going here:
http://jsfiddle.net/hpP45/
I try to decode first(google bse64 decoder )
https://www.base64decode.org/
and save decoded binary data as an jpeg file and open it.
if it does not open then i guess,there might be issue on your base64 encoding

Image Save and Retrieve in SQL Server in asp.net using c#

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();

Categories