Reputation: 19
The image is not loading from the given path in asp.net here, is the scenario. I have uploaded an image into the folder using asp.net and inserted it's path to SQL server database, but when I try to fetch the image from the path which I have in my asp application "The path is correct" but image failed to load. There are no errors.
Here Is the Code for Uploading Data
if (FileUpload1.HasFile && TextArea1.Value != null)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string path = Server.MapPath("/admin/images/" +fileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("/admin/images/" + fileName));
//Response.Write("<script>alert('" + path + "');</script>");
string ta1 = TextArea1.Value;
string sql = "UPDATE homep SET img = '" + path + "', description= '" + ta1.Replace("'", "''") + "' WHERE id = 1;";
cmd = new SqlCommand(sql, con);
if (cmd.ExecuteNonQuery() > 0)
{
Response.Write("<script>alert('Updation Success ..!');</script>");
}
}
here is the code for fetching data
dr.Read();
Response.Write("<img src='"+dr["img"].ToString()+"' class='img-responsive'/>");
dr.Close();
This Image shows final output as i am getting content but not getting image from path
Upvotes: 1
Views: 1930
Reputation: 4191
use ~ like this:
Server.MapPath("~/admin/images/" +fileName)
Upvotes: 0
Reputation: 2585
You serve a physical path on the servers harddrive to the browser, which the browser of the client can't open. You should build an actionmethod that serves the image and provide the url to that actionmethod in the src="" from your image.
for example:
Response.Write("<img src='/Serveimage/?path="+dr["img"].ToString()+"' class='img-responsive'/>");
and then create the 'ServeImage' actionmethod:
public FileResult ServeImage(string path)
{
var bytes = System.IO.File.ReadAllBytes(path);
return File(bytes, "image/png");
}
Upvotes: 1