Imagebutton not display image - c#

once i click button, my image1 will display an image;
when i set my imagePath to
Server.MapPath("~/SME IMAGE/anonymous_avatar.gif");
my url not work
but when i set my path to
"~/SME IMAGE/anonymous_avatar.gif"
my url work
so basically what happen to my Server.MapPath?
try
{
string imagePath = Server.MapPath("~/SME IMAGE/anonymous_avatar.gif");
Image1.ImageUrl = imagePath;
Response.Write("success");
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}

Server.MapPath it translates the "web" path into your local path.
So Server.MapPath("Server.MapPath") it will give the local location of your file.
You are assigning this to the ImageUrl property, but this will be translated to something like "www.mywebsite.com/C:\wwwroot\somefile.gif"

Try not to set the Server.MapPath - just use:
Image1.ImageUrl = "~/SME IMAGE/anonymous_avatar.gif";
Maybe make sure the url exists, and maybe add %20 instead of the space in the path. (Also try to avoid spaces in paths)

Server.MapPath returns the physical file path that corresponds to the specified virtual path on the Web server. So when you setting
string imagePath = Server.MapPath("~/SME IMAGE/anonymous_avatar.gif");
it could return something like C:\Inetpub\wwwroot\website\SME IMAGE\anonymous_avatar.gif which is actually a physical path to the file.
Image.ImageUrl property accepts the URL of an image to display in the Image control. You can use a relative or an absolute URL. MSDN says:
A relative URL relates the location of the image to the location of
the Web page without specifying a complete path on the server. The
path is relative to the location of the Web page. This makes it easier
to move the entire site to another directory on the server without
updating the code. An absolute URL provides the complete path, so
moving the site to another directory requires that you update the
code.

Related

ASP.NET: Image URL is correct, but image does not display

I know this has been asked before, as it's a rookie question, but the other answers on here did not clarify it for me. I an uploading a file then providing a preview. The click event of my upload button is this:
protected void UploadFile (object sender, EventArgs e) {
string folderPath = Server.MapPath ("~/Uploads/");
// If folder does not exist, create it.
if (!Directory.Exists (folderPath))
Directory.CreateDirectory (folderPath);
//Save the File to the Directory (Folder).
FileUpload.SaveAs (folderPath + Path.GetFileName (FileUpload.FileName));
//Display the Picture in Image control.
imgItem.ImageUrl = folderPath + Path.GetFileName (FileUpload.FileName);
}
The upload works fine, but the image control (imgItem) does not display the picture. When I trace it, the URL looks perfect. The URL is:
"C:\\MyStuff\\Source\\Inventory\\Inventory\\UserInterface\\Uploads\\sample.jpg"
That should have worked. What in the world am I doing wrong?
EDIT: I don't feel that this is a good solution at all, but I've found that the program works as expected if I change the last line to this:
imgItem.ImageUrl = "~/Uploads/" + Path.GetFileName (FileUpload.FileName);
Don't anyone have a cleaner, less hardcodey solution?
Well, the
"C:\MyStuff\Source\Inventory\Inventory\UserInterface\Uploads\sample.jpg"
is actually the file path, not the URL. Since you use the word "URL", I assume that you're building a web site. Which means you need an proper URL (e.g. http(s)://yourdomain.com/Source/Inventory/..../sample.jpg)
If you don't how what is the url for your file path, you can use virtual folder in IIS to map it. https://docs.kentico.com/k11/installation/deploying-kentico-to-a-live-server/creating-virtual-directories-and-application-pools-in-iis-7-5-and-7-0
imgItem.ImageUrl = "~/Uploads/" + Path.GetFileName (FileUpload.FileName);

File.Delete isn't working to delete image from sub folder

In our ASP.NET program a user can upload an image to a folder. The location of the image (including the name of the upload folder which is in the root directory) is stored as a variable called "path", ie. "Uploads/fileName.jpg".
To remove the image:
if (File.Exists("~/" + path))
{
File.Delete("~/" + path);
}
However, it fails to run because it can't verify that the file exists. Through some testing we noticed it's looking for "path" in the "system32" directory. Why would this be?
You need to use Server.Map path to ensure that the Tilde is resolved correctly.
MSDN Article is here -> http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Your code would become
var fixedPath = Server.MapPath("~/" + path);
if (File.Exists(fixedPath))
{
File.Delete(fixedPath);
}
The File class is not aware of the IIS directory mapping, so it won't understand ~ correctly. You have to first use a method to map the app relative path to a local path with Server.MapPath

How to display image which is stored on Local drive or network drive?

I have a asp page in which i have to display the image which is stored in my local disk C: and in some cases from network drive
Example path:--C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg
I have done the following code in c# code behind
Image image = new Image();
image.Height = 150;
image.Width = 150;
string path = #"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";//this path will come from database dynamically this is for test only
image.ImageUrl = path;
this.Controls.Add(image);
but image is not showing up so i stumbled upon the this SO Question and i updated my code as below
for page which is showing image
Image image = new Image();
image.Height = 150;
image.Width = 150;
string path = #"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
image.ImageUrl = "ImageWriter.aspx?path=" + path;
this.Controls.Add(image);
and for proxy page
Response.ContentType = "image/jpeg"; // for JPEG file
string physicalFileName = Request.QueryString["path"];
Response.WriteFile(physicalFileName);
this is working fine but i have two question
1) Why the file is accessible from the physical path while proxy from page but other page cannot able to access it ?
2) And is there any other way to do it ?
Any help would be great thanks.
The images are not available because that path has no relative context to an asp.net site user through a browser who will probably be on another PC and network. To fix this, all you need to do is create an ASHX handler page that fetches the images that are on the server's local drive or network and serve them as an image to the browser:
public void ProcessRequest(HttpContext context)
{
string imgName = context.Request.QueryString["n"];
context.Response.ContentType = "image/png";
string path = #"C:\Users\Public\Pictures\Sample Pictures\" + imgName;
Image image = Image.FromFile(path);
image.Save(context.Response.OutputStream, ImageFormat.Png);
}
And then in your asp just point an image url to the ashx:
image.src = "images.ashx?n=penguin.jpg";
1) Why the proxy page can access the physical path but other page cannot able to access it ?
The other page can. However, the other page isn't accessing the file. It's just setting the file's path to the HTML output for the client (web browser) to access it. Resulting in this:
<img src = "C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg" />
Since the user doesn't have access to that file, the img tag won't work. The purpose of the "proxy" page is to serve the content of the file from a location which the user can access, that location being the proxy page.
2) And is there any other way to do it ?
Nope. Either the user has to have direct access to the file via some virtual path on the web server, or you have to have a proxy which reads the file's contents and sends it to the user. It has little to do with your C# code and everything to do with what the user can see on the web server. Unless the file is in a web-accessible folder, the user can't see it.
This is a very common and standard approach to securing files behind a web application. Sometimes, for example, you want to check the user's authorization before allowing them to see a file. If the file were publicly accessible, they could just go to it directly. But if there's a proxy page between the user and the file then that page can enforce authorization.
On my experience, the best way, just to avoid all the security problem that finally make impossible the above solutions, is to setup a local website and set the image url like this: image1.ImageUrl="http://pcname/photofolder/myphoto1.png".
pcname is the name of the local web server and the path is the path of a virtual directory set in the local IIS. To setup a local IIS is very simple, google have tons of tips, and to setup a virtual directory is only needed to enter the iis, open the default website, right-clik on "add a new virtual directory" and set the name (photofolder in my example) and make it point to a physical local disk folder and the trick is done. This has also a vantage, that's to say that you can access that folder in all clients connected to the lan.

How we Redirect one Page to AnotherPage with Server.MapPath

My Code is Response.Redirect(Server.MapPath("~/ReportPage.aspx"));
you don't need MapPath here, since you have relative path you can directly call Response.Redirect
Response.Redirect("~/ReportPage.aspx");
Server.MapPath will return physical path of given file. For example when we need to read TEXT file inside root folder
var lines = File.ReadAllLines(Server.MapPath("~/temp.txt"));
But in your case no need of a Server.MapPath
Why are you using MapPath for this? Redirects are handled by the client so mapping to the physical file won't work.
Simply do:
Response.Redirect("~/ReportPage.aspx");
Response.Redirect, redirects to the virtual path to a location not the physical path. Whereas Server.MapPath returns the physical path which is not valid in this context.
You just need to use like this
Response.Redirect("~/ReportPage.aspx");
Don't use Server.MapPath.
Response.Redirect("~/ReportPage.aspx");

Checking if image exist in my local resources

net/C# application I have list of items.
In the code behind:
I want to assign a picture from my local resources for each item. the items name and the picture names are the same.
The pictures are all in a "image" folder in my project.
Example of how I assign a picture to an item:
Item1.PictureUrl = "images/items/" + item1.Name + ".jpg";
I have items that don't have pictures. I want to assign for them a default picture.
I tried to check if the picture exists using this:
foreach(ObjectItem item in ListOfItems)
{
if(File.Exists("images/items/"+item.Name+".jpg"))
item.PictureUrl = "images/items/"+item.Name+".jpg";
else
item.PictureUrl= "images/Default.jpp";
}
But the File.Exists method is always returning false, even if the picture exist.
I also tried to use '\' instead of '/' but didn't work
How can I do it?
Thank you for any help
You need to convert the relative file path into a physical file path in order for File.Exists to work correctly.
You will want to use Server.MapPath to verify the existence of the file:
if(File.Exists(Server.MapPath("/images/items/"+item.Name+".jpg")))
Also, when you use Server.MapPath, you should usually specify the leading slash so that the request is relative to the web application's directory.
If you don't provide the leading slash, then the path will be generated relative to the current page that is being processed and if this page is in a subdirectory, you will not get to your images folder.
.Net Core Solution
1- Write this at the top of your View (Injecting IHostingEnvironment here);
#inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
2- Write this to the place of image(Doing existence check);
var path = System.IO.Path.Combine(hostingEnv.WebRootPath, "MyFolder", "MyImage.jpg");
if (System.IO.File.Exists(path))
{
<img class="img-fluid" src="~/MyFolder/MyImage.jpg" alt="">
}
var path = $#"C:\Fotos\Funcionarios\1.Png";
FileInfo file = new FileInfo(path);
if (file.Exists.Equals(true))
{
//faz algo
}

Categories

Resources