The image is not displaying using asp.net - c#

In the below code i have a image i have pass image url from codebehind but it is not displaying the image.
The url location is C:\Search\Searchdoc\Documents\Desert.jpeg
public string strClientName = "Searchdoc";
public string strDocumentFolder = "Documents";
string Imgdocname = SearchDoc.DocumentName;
string fileExt = System.IO.Path.GetExtension(Imgdocname);
fileExt = fileExt.ToLower();
if (fileExt == ".jpeg" || fileExt == ".jpg")
{
docimg.Src = "~/" + Search+ "/" + strClientName + "/" + strDocumentFolder + "/" + Imgdocname;
docimg.Visible = true;
}
else
{
docimg.Src= "~/Search/Searchdoc/Documents/image.jpeg";
docimg.Visible = true;
}

Well for a start, you are using the ~ character which indicates the root directory of the application.
Since you are saying that the image is in C:\Search\Searchdoc\Documents\ then that won't be found, since your code is actually looking in projectRoot\Search\Searchdoc\Documents
As for how to get this image to show in a webpage, it won't simply work for accessing it from the C drive. IIS will not serve images that aren't in the web site folder structure. I would suggest moving it into the website.
If you need to keep it stored in a folder outside your website, you would need to look at streaming it, or using a sort of proxy page. Have a look at the answer here: How to display image which is stored in local drive? to get an idea of the proxy method

Related

How to display more than one photo from flicker api in WebBrowser

I am looking for solution how to display more than one photo in my webbrowser using winforms. I am using Flickr API to make my simple photo filtering application. I am using this method: https://www.flickr.com/services/api/flickr.photos.search.html
With this method, I get XML file which shows 100 photos components and later from this XML I am building my Url string.
My code looks like:
StringBuilder abc = new StringBuilder();
XmlTextReader sr = new XmlTextReader(Urlstring);
while (sr.Read())
{
if ((sr.NodeType == XmlNodeType.Element && (sr.Name == "photo")))
{
if (sr.HasAttributes)
abc.Append("https://farm" + sr.GetAttribute("farm") + ".staticflickr.com/" + sr.GetAttribute("server") + "/" + sr.GetAttribute("id") + "_" + sr.GetAttribute("secret") + ".jpg");
break;
}
}
With this code I get only one photo of that XML file. I want to get more, but when I remove break;. Webbrowser says there are no photos to display. Maybe you have any solution how to build string and read that xml that I could build more that one url and display in webbrowser application?
Thanks in advance.

Add downloaded images to resource folder

I have downloaded an image with the following code:
bool pageExists = false;
// Check if webpage exists
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://image.tmdb.org/t/p/w780" + imagePath);
request.Method = WebRequestMethods.Http.Head;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
pageExists = response.StatusCode == HttpStatusCode.OK;
}
// Download image
if (pageExists)
{
string localFilename = #"C:\Users\Giri\Desktop\giri" + id + ".jpg";
using (WebClient client = new WebClient())
{
client.DownloadFile("http://image.tmdb.org/t/p/w780" + imagePath, localFilename);
}
}
For now, I have just been saving this image on my Desktop.
My question is how do I go about storing this image in my WPF application programmatically within a resources folder or a folder I have generated myself? The images should persist in that the next time the application is run, the added images should remain.
Is there an accepted place I should be storing my images?
Thanks for your help.
Please use AppDomain.CurrentDomain.BaseDirectory. Which will give you the directory of your executable. Even in deployed code this should give you the right value. But other values like Environment.CurrentDirectory can give different value based on from where you are calling it etc.
See this question Best way to get application folder path

how to display image using imageurl in C#

if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}

Upload image worked in local but not work in my hosting

I have a project ASP MVC.In my project i have a form for upload image i used
string path = System.IO.Path.Combine(Server.MapPath("~/images/"));
if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
string url = path + home.Image;
if (System.IO.File.Exists(path + home.Image))
{
System.IO.File.Delete(path+home.Image);
}
FileInfo FInfo = new FileInfo(Request.Files[0].FileName);
string filename = "sample";
string ImagePath = path;
Request.Files[0].SaveAs(ImagePath + filename + FInfo.Extension);
}
Above this code in my local system perfectly .I hosted my project in my site.But it now working in my site.
Any one know please help me
Thanks
Please check your path for image folder,
Please check that you have write permission on folder in which you uploading image,
If you do not have permission then go to security tab and allow full control to everyone,

File Uploading using Server.MapPath() and FileUpload.SaveAs()

I have a website admin section which I'm busy working on, which has 4 FileUpload controls for specific purposes. I need to know that , when I use the Server.MapPath() Method Within the FileUpload control's SaveAs() methods, Will it still be usable on the web server after I have uploaded the website? As far as I know, SaveAs() requires an absolute path, that's why I map a path with Server.MapPath()
if (fuLogo.HasFile) //My FileUpload Control : Checking if a file has been allocated to the control
{
int counter = 0; //This counter Is used to ensure that no files are overwritten.
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]); // This is the part Im wondering about. Will this still function the way it should on the webserver after upload?
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++; //Here the counter is put into action
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
if (fuLogo.PostedFile.ContentLength > 409600 ) //File must be 400kb or smaller
{
cvValidation.ErrorMessage = "Please use a picture with a size less than 400 kb";
cvValidation.IsValid = false;
}
else
{
if (fuLogo.HasFile && cvValidation.IsValid)
{
fuLogo.SaveAs(logo); //Save the logo if file exists and Validation didn't fail. The path for the logo was created by the Server.MapPath() method.
}
}
}
else
{
logo = "N/A";
}
If you intend to save the files in
a directory on your web server , then
the Server.MapPath() will be the suitable
solution.
string dirPath = System.Web.HttpContext.Current.Server.MapPath("~") + "/Images/Logos/"+ fileBreak[0] + counter.ToString() + "." + fileBreak[1];
Look Here
if you intend to save your files out
the web server then
Use a full path, like "c:\uploads"
and be sure that the web process has
permission to write to that folder,I suggest you store the path itself in the web.config file in this case.
yes, that can be used after saving file and when you try retrieve that file...
Server.MapPath("~/Images/Logos/" + uploadedFileName);
Yes it should still work as Server.MapPath uses the relative values and returns the complete physical path.
It's one line of code:
FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName);

Categories

Resources