Hello Friends i am storing an image via URL in database but when i retrieve it on Image Control of asp.net it doesn't show the image please help
Profile.aspx.cs
con.Open();
string str = "SELECT * FROM [aspdotnetpractice].[dbo].[Users] where Username ='" + lblHowdy.Text + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
Image1.ImageUrl = Server.MapPath(reader[8].ToString());
Label1.Text = reader[1].ToString();
Label2.Text = reader[2].ToString();
Label3.Text = reader[3].ToString();
Label4.Text = reader[6].ToString();
Label5.Text = reader[4].ToString();
reader.Close();
con.Close();
}
Make sure you save path value like "ImageFiles/test.jpg" or filename only like "test.jpg". Dont save to path field a complete local path like "c:\…\test.jpg". In imageurl you should use virtual path instead physical path.
The Server.MapPath returns a file name. On the other hand, Image.ResolveUrl expects a valid url.
You'd rather want something like
Image1.ImageUrl = Page.ResolveUrl("~/ImageFiles/") + fi.Name; // You just need to pass name or something similar.
Related
I want to insert/delete,update image in sql database using asp.net. My code of inserting is:
Stream strm = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(strm);
byte[] img = br.ReadBytes(Convert.ToInt32(strm.Length));
imgDetail.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(img, 0, img.Length);
imgDetail.Visible = true;
try
{
cmd = new SqlCommand("insert into Persons (id,Name,Surname,Address,Phone,Picture,Department) values (#id,#Name,#Surname,#Address,#Phone,#img,#Department)",con);
cmd.Parameters.AddWithValue("id", txtId.Text);
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Surname", txtSurname.Text);
cmd.Parameters.AddWithValue("Address", txtAddress.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("img", img);
cmd.Parameters.AddWithValue("Department", Department.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I think something went wrong with added image, maybe i do this wrong .Now when i click on some record in my gridview, all data of the record displays in the textboxes, but i cant do display image in imagebox. how can i do this?
this is part of displaing data in textboxes:
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex == GridView1.SelectedIndex)
{
GridViewRow row1 = GridView1.SelectedRow;
txtId.Text = row.Cells[0].Text;
txtName.Text = row.Cells[1].Text;
txtSurname.Text = row.Cells[2].Text;
txtAddress.Text = row.Cells[3].Text;
txtPhone.Text = row.Cells[4].Text;
Department.Text = row.Cells[5].Text;
Image.??????
The "Image" control is a just a wrapper around the standard <img> HTML-tag. So obviously it does not have any binary property, that you can set to a byte-array.
But you go with a "data" uri.
Here's an idea for you:
Image.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])imagedata);
I am trying to load an image through label using this code
private void getData()
{
SqlConnection conn = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
conn.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT empName,empLname,empMi,empImage
FROM employees
WHERE empName = '"+ ddlAvail.SelectedItem.Value.ToString() +"'", conn);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblName.Text = rdr.GetValue(0).ToString();
lblLname.Text = rdr.GetValue(1).ToString();
lblMi.Text = rdr.GetValue(2).ToString();
lblImage.Text = "<img runat='server' src='" + rdr.GetValue(3).ToString() + "'></img>";
}
}
conn.Close();
}
every time I select a dropdownlist value it generates me set of sql data.My only problem is the image.Cause it wont load any image at all.The filepath on my visual studio and image name is correct.
This is an example of my image
../Images/Profile/logo.jpg
I save the images filepath on my database.
Your code looks fine
Make sure the file path your are retrieving from the database exists and the path isn't returning any unwanted characters.
That is:
rdr.GetValue(3).ToString() //should return the right path (string)
It should be fine. Hope this helped
It won't ever show the image because all that your code is doing is setting the text on the label.
If you want to display the image try this , or this.
this is so that when I need to upload a right an image to an article so it must delete the old image
and it must be clear in the folder where the image is located,
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
problem is that I need to find the image in the column in the database where the entity who should delete the picture
Access to the path 'C:\Users\198407\Documents\Visual Studio 2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
my pictures located here: /img/bimg/hello.png
how it looks when I load to the server
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
ImageNet.FluentImage img = ImageNet.FluentImage.FromStream(FileUploadImg.FileContent);
img.Resize.Scale(360).Save(Server.MapPath(url + unikID + ".png"));
if (File.Exists(Server.MapPath(url + unikID + ".png")))
{
cmd.CommandText = "UPDATE aktiviteter SET navn = #navn, sted = #sted, indhold = #indhold, img = #img, rubrik = #rubrik, retbrugerID = #retbrugerid WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#navn", navn);
cmd.Parameters.AddWithValue("#sted", Sted);
cmd.Parameters.AddWithValue("#indhold", Indhold);
cmd.Parameters.AddWithValue("#img", unikID);
cmd.Parameters.AddWithValue("#rubrik", rubrik);
cmd.Parameters.AddWithValue("#retbrugerid", brugerid);
}
Since you are getting this error -
Access to the path 'C:\Users\198407\Documents\Visual Studio
2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
I would suggest , granting read/write access to this user = IIS_IUSRS for required directory.
Read more helpful link
I'm trying to create sql database that contains
Image Id (int)
Imagename (varchar(50))
Image (image)
and in aspx write in upload button this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
When I'm uploading a new image I need to first check if this image already exists in database and if it doesn't exist save that in database.
Please how I can do that?
Add a method that is responsible for checking if the filename already exists in the table.
private bool FileExists(string imageName)
{
using (SqlConnection conn = new SqlConnection()) // establish connection
{
using (SqlCommand cmd =
new SqlCommand("select 1 where exists(select Id from Image where ImageName = #)", conn))
{
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imageName;
return cmd.ExecuteNonQuery() > 0;
}
}
}
Then I would call this like so
if (fileuploadImage.HasFile && !FileExists(txtImageName.Text))
{
...
string cmd ="if not exists (select * from Image where ImageName= #imagename); ";
\\if you want to check image data
\\ (select * from Image where SUBSTRING(ImageName, 1, 8000)= SUBSTRING(#imagename, 1, 8000) );
string cmd += "INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
SqlCommand cmd = new SqlCommand(cmd, connection);
If you want to verify imagedata, You can try to use DATALENGTH as first line of check for the two images.
If the DATALENGTH is different, then you suppose to have a "different" picture".
You can also use SUBSTRING(Image, 1, 8000) to check first 8000 bytes.
And also SUBSTRING(Image, DATALENGTH(Image) - 7999, 8000) to check last 8000 bytes.
One of the fastest ways is to do an UPDATE and then INSERT if update returns no updates.
string cmd = #"UPDATE Image SET Image = #imagedata WHERE ImageName = #ImageName
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
Or if query on Image itself:
string cmd = #"UPDATE Image SET ImageName = #ImageName WHERE Image = #imagedata
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
I have an asp.net web forms site, I am looking to create a control that allows the user to browse for an image then save the image into the database. I know that saving images into a database is bad practice, but thats what I've been told to do!
Does anyone have any suggestions for the best approach to do this?
thanks
Essentially all you need is a FileUpload control and some code to save it to the database. (And you'll want to do some input checking as well, naturally.) There's a pretty old tutorial which explains the concept well here. This one is a little more recent. But there's no shortage of others.
from a sample:
var intDoccumentLength = FileUpload1.PostedFile.ContentLength;
var newDocument = new byte[intDoccumentLength];
var stream = FileUpload1.PostedFile.InputStream;
stream.Read(newDocument, 0, intDoccumentLength);
var sqlConnection = new SqlConnection(sqlConnectionString);
sqlConnection.Open();
var sqlQuery = "INSERT INTO dbo.DocumentData (DocName, DocBytes, DocData, DocCreatedAt) VALUES (#DocName, #DocBytes, #DocData, #DocCreatedAt);"
+ "SELECT CAST(SCOPE_IDENTITY() AS INT)";
sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlCommand.Parameters.Add("#DocName", SqlDbType.NVarChar, 255);
sqlCommand.Parameters.Add("#DocBytes", SqlDbType.Int);
sqlCommand.Parameters.Add("#DocData", SqlDbType.VarBinary);
sqlCommand.Parameters.Add("#DocCreatedAt", SqlDbType.DateTime);
sqlCommand.Parameters["#DocName"].Value = FileUpload1.PostedFile.FileName;
sqlCommand.Parameters["#DocBytes"].Value = intDoccumentLength;
sqlCommand.Parameters["#DocData"].Value = newDocument;
sqlCommand.Parameters["#DocCreatedAt"].Value = DateTime.Now;
var newDocumentId = (Int32) sqlCommand.ExecuteScalar();
sqlConnection.Close();
There is fileupload tool available in toolbox. You just have to writ the below code in the click event of button..
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
and I hope you have an image column in your database so then just insert the string sl1 in your insert query..