I have an Image control on my .aspx page and I want to set the ImageUrl to something like this:
<asp:Image ID="imgLogo" ImageUrl="C:\ExternalImages\logo.jpg" runat="server" />
But this doesn't work. I read about the ImageUrl property on MSDN and it says that the url could have either be an absolute or relative path. But how can i set the complete path like shown above?
"Absolute" means absolute from the client's perspective, as in http://foo.com/images/logo.jpg or /images/logo.jpg. The difference is either the fully-qualified domain name or the leading "/", which tells the browser to load that path from the root, or domain-level.
"Relative" means no leading slash, and tells the browser to navigate to the path using the current folder as the starting point. So ../images/logo.jpg is a relative path meaning "relative to the current folder, move up one folder, then down into the images folder, then logo.jpg"
The example you've shown instructs the end-user's browser to load that path from their own machine, which in most cases won't work since they don't have that path or file :)
By absolute url, they mean the entire IIS path to the URL (Not your disk directory path). (i.e. http://yourVirtualDirectory/ExternalImages/logo.jpg).
Create a virtual directory on your IIS hosting machine that points to C:\ExternalImages. Use that virtual directory path in your control.
The ImageUrl is not the computer's path but a Url path: http://www.something.com/logo.jpg" or "/logo.jpg"
You could as well get the image from the disk, but you have to add: file:// but will not run in any other machine than were you are developing-
Absolute and relative URL reffers to the relation on the server.
ex: http://mydomain.se/mysite/images/image.gif is an absolute path
/images/image.gif is a relative path.
Relative in the way that you page is located in the Mysite directory on the server.
The reason for using relative paths is that it makes it easier to move the site around,
The reason to use a absolute path is that you can move the "myimage.html" to a subdirectory without breaking the url.
Absolute means Absolute from within your project, relative means relative the current position e.g. ../../Images/logo.jpg. You are best to use absolute for greatest flexibility e.g. ~Images\logo.jpg. The tilde ~ gets replaced automatically with the correct relative path at runtime.
That folder must be inside your virtual folder, so you can do:
<asp:image imageurl = "/ExternalImages/logo.jpg" runat="server">
Another option is to create a page which can read that file, so you could to write:
<asp:image imageurl = "MyImage.aspx?name=logo.jpg" runat="server">
And your MyImage.aspx.cs will look like:
protected void Page_Load(object sender, EventArgs e)
{
string basePath = #"c:\ExternalFolder";
string combined = Path.Combine(basePath, Request.QueryString["name"]);
if(!basePath.Equals(Path.GetPathRoot(combined),
StringComparison.InvariantCultureIgnoreCase))
throw new System.Security.SecurityException();
using (FileStream image = new FileStream(combined, FileMode.Open))
{
int length = (int)image.Length;
byte[] buffer = new byte[length];
image.Read(buffer, 0, length);
Response.BinaryWrite(buffer);
}
}
But note that code can lead to injection problems, as you can pass a "..\" into name parameter and get access to files outside that folder.
So, place that folder inside your virtual directory.
EDIT: To make clear: My suggestion is to place your ExternalFolder inside your virtual directory. That's make you life easier.
Sometimes isn't possible to move a folder. So I also updated code above to deal with non canonical file names.
Related
In web application, i am trying to display image in .aspx page, for that i write code like this in page_load event ,
Image1.ImageUrl = #"C:\Users\Public\Pictures\Sample Pictures\Koala.JPEG";
but image is not displaying, can you help me thank you.
there is problem with the path of image ...you need to give relative path for image rather than physical path
something like this
Image1.ImageUrl="~/Images/Bird1.jpg"
here image is in the Images folder of the application. i.e.which is part of project
First create a Images folder in your Solution Explorer. Then store your image in that folder and refer like as below.
Example
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/Bird1.jpg" />
Check in deatil : Image Control Example
You cannot use your local path as the path to your image, instead place the web site url with a relative path to the image
Right now, I'm having trouble.
First of all I have a page, let's call it "http://blah.com/login".
That obviously goes strait to "index.asp"
A line of Main.asp:
<!--#include file="resource/menu.asp"-->
Page top includes all of what I need for my menu... so:
Part of resource/menu.htm:
<div id="colortab" class="ddcolortabs">
<ul>
<li><span>Main</span></li>
...
</ul>
</div>
<!--Main drop down menu -->
<div id="dropmain" class="dropmenudiv_a">
Announcements
Contact Information
Meeting Plan
Photo Gallery
Upcoming Events
</div>
Let's say I click on the "announcements" (http://blah.com/login/main/announcements.asp) link... Now I'm at the announcements page!
But wait, I include the same menu file. Guess what happens:
I get sent to "http://blah.com/login/main/main/announcements.asp
Which doesn't exist...
My solution:
Make a menu_sub.asp include for any subpages.
But wait a second... this WORKS, but it gets REALLY REALLY messy... What can I do to use just one main "menu.asp" instead of "menu_sub.asp"? using "/main/announcements.asp" WON'T be an option because this is a web application that will be on different directories per server.
There is no magic bullet fix. Here is how I would do this.
Create a separate include file that DIM's and Initializes global variables called info.asp
Inside info.asp DIM a variable called strRelativePath and initialize it to ""
Include info.asp at the top of each asp page above the menu.asp include
Modify menu.asp and include <%=strRelativePath%> in all the urls
Inside each asp page set strRelativePath as necessary:
<!--#include file="includes/info.asp"-->
strRelativePath = "Login/"
<!--#include file="resource/menu.asp"-->
Add this function to your menu.asp:
Function GetApplicationPath()
GetApplicationPath = Mid(Request.ServerVariables("APPL_MD_PATH"), Len(Request.ServerVariables("INSTANCE_META_PATH")) + 6) & "/"
End Function
Dim prefix: prefix = GetApplicationPath()
Now structure your references in the menu.asp using:
Announcements
This will make these references absolute but they will vary appropriately with whatever virtual folder path the website has your ASP application installed under.
There is a similar question here where the highest rated answer states that you can find the root with the following function:
Function ToRootedVirtual(relativePath)
Dim applicationMetaPath : applicationMetaPath = Request.ServerVariables("APPL_MD_PATH")
Dim instanceMetaPath : instanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
Dim rootPath : rootPath = Mid(applicationMetaPath, Len(instanceMetaPath) + Len("/ROOT/"))
ToRootedVirtual = rootPath + relativePath
End Function
You can then call it:
ToRootedVirtual("/")
or
ToRootedVirtual("/index.asp")
etc. to return the root from the server.
You can use Virtual instead of File because Virtual accepts an absolute path from the root directory, not relative like File.
Like this:
<!--#INCLUDE VIRTUAL="/resource/menu.asp"-->
Also, make sure your IIS settings allow Includes, See this link for details:
http://tech.mikeal.com/blog1.php/server-side-includes-for-html-in-iis7
This can be fixed with the HTML base tag:
Add this tag in the beginning of each page:
<base href="http://blah.com/login">
I have an ASP.NET 2010 app and am trying something very simple. I use Image control through out and basically wanted to say, before I assign an image to it (from a class) look for the image; if it's not there, use the default no_image jpeg I have. I have verified the image is there ad nauseam. If I set the property in the IDE to point to this image, it'll display. However, if I set it programmatically, even if I hard-code the path programmatically, it doesn't show.
Forgettign about getting the proper path and all that, (of which Ive tried several things) I can;t even hard code the relative path. Here I copied & pasted the relative path from the properties window...
Image1.ImageUrl = "~/UploadedPictures/Users/no_profile_picture.jpg"
This doesn't work. It translates into src="../../UploadedPictures/Users/no_profile_picture.jpg" which is correct but the image doesn't display.
If I hardcode the absolute path it doesn't work either...
Image1.ImageUrl = "C:\Inetpub\wwwroot\myApp\UploadedPictures\Users\no_profile_picture.jpg"
You have to use a virtual path. Try adding ~ before your path.
Image1.ImageUrl = "~/UploadedPictures/Users/no_profile_picture.jpg"
We have a multilingual site, or culture-sensitive, and some of the static content now needs to be targeted; for this I'm using themes as it seems the easiest way to achieve what I want, but I can't for the life of me get the images to pick up.
I'm setting the theme in code-behind, and thought at first that maybe this was the issue, but on checking up it looks like I'm doing the right thing (setting on Pre-Init).
I expect to be able to reference images using relative paths where App_Themes/ThemeName/ is automatically resolved, such as:
<asp:Image runat="server" ImageUrl="images\image.jpg"/>
For whatever reason, however, the image isn't being pulled through at all.
This is the code we have in place for setting the theme (the only really relevant part, I'm sure, being the Theme = CurrentSite.CultureName, which is applied successfully):
Private Sub SetTheme()
Dim themesPath = Server.MapPath("~/App_Themes")
If Directory.Exists(themesPath) Then
Dim themePaths = Directory.GetDirectories(themesPath)
Dim themePathInfo As DirectoryInfo
For Each _path In themePaths
themePathInfo = New DirectoryInfo(_path)
If Not themePathInfo Is Nothing Then
If themePathInfo.Name = CurrentSite.CultureName Then
Theme = CurrentSite.CultureName
Exit For
End If
End If
Next
End If
End Sub
In the above code, CurrentSite.CultureName would be a language culture name (for example, en-gb, or nn-no) that does have an existing corresponding theme folder containing all required resources.
Pages do have EnableTheming set to True. Also, I have tried removing the theme-setting code and applying the theme in the page using Theme="en-gb" to no avail.
Is there anything immediately evident as to why the URLs aren't resolved?
Use a Skin file to do this. Change your Image tag to:
<asp:Image runat="server" SkinID="SomeImage/>
And in your App_Themes\MyTheme\ folder, add a new Skin file (MyTheme.skin) and add this:
<asp:Image runat="server" SkinID="SomeImage" ImageUrl="images\image.jpg"/>
This image skin now points to image.jpg within the App_Themes\MyTheme\ folder.
For dynamic images you can do this in your BasePage (assuming you have one):
public string ThemePath { get { return "~/App_Themes/" + this.Theme + "/"; } }
public string MapThemePath(string relativePath)
{
return string.Format("{0}{1}", this.ThemePath, relativePath);
}
But, since I can't see what you're actually doing, I can't say this is the recommended solution. In general your theme contains only things needed or layout and display. You're talking about dynamic images which, to me, doesn't sound like it belongs in a theme? Not sure, just a thought.
I have a website on GoDaddy. All permissions are set correctly and the image DOES exist. However when the page loads the image for the item selected does not show. Here is my code
imagepath = "~/spaimages/" + currentSpaModel.Name.ToString() + ".png";
if (File.Exists(Server.MapPath(imagepath)))
{ this.spaimage.ImageUrl = Server.MapPath(imagepath); }
spaimage is an ASP control and thr URL that the image is set to is D:\hosting\xxxxxxx\calspas\spaimages\modelname.png
What am I doing wrong.
The file path D:\hosting\xxxxxxx\calspas\spaimages\modelname.png is the folder where the image resides on the web server. You are sending this as the <img> tag's src attribute, which tells the browser, "Go get the image at D:\hosting\xxxxxxx\calspas\spaimages\modelname.png." The browser cannot go off to the D drive of the web server, so it looks on its own D drive for that folder and image.
What you mean to do is to have the <img> tag's src attribute be a path to a folder on the website. You're just about there - just drop the Server.MapPath part when assigning the image path to the ImageUrl property. That is, instead of:
this.spaimage.ImageUrl = Server.MapPath(imagepath);
Do:
this.spaimage.ImageUrl = imagepath;
See if that works.
Thanks
Often, if an image "does not show" (I assume a red-x-equivalent is being displayed to show "broken image"), I right-click the broken image, copy the URL and open the URL in a separate browser window.
This way, when the image is being generated by some script, I see any error text that the script might have shown. If not, the real image would be displayed.
In addition, add an else block to the
if (File.Exists(Server.MapPath(imagepath)))
like
else
{
Response.Write(string.Format(
"File does not exist at '{0}'.",
Server.MapPath(imagepath)));
}
For debugging purposes.