how to load image with relative path in bitmap - asp.net

i want to upload image int the bitmap object from asp.net, the image is location under
/uploadedimages/sampleimage.jpg
whenever i use below code to load image in bitmap, i gets error saying Parameter not valid.
Bitmap b = new Bitmap("/uploadedimages/sampleimage.jpg") // this path is coming from database holded in variable
i tried to replace the slashes in path to "\" still that does not work.
can anyone tell me what could be the reason for the error and the possible resolution.

Use Server.MapPath. And it's a good practice to use the tilde char ~ to specify the web application root.
Bitmap b = new Bitmap(Server.MapPath("~/uploadedimages/sampleimage.jpg"));

if uploadedimages directory is in your App_Data folder then you should append the App_Data absolute path to your path:
Bitmap b = new Bitmap(Path.Combine(Server.MapPath("~/App_Data"), "/uploadedimages/sampleimage.jpg"));

You can use server.MapPath, pass Url string as given below.
Server.MapPath("../images/image.gif")

Related

Display image using string builder in ASP.Net

my need is to display an image in a web page using string builder. i know through this snippet sb.Append("<img src=\"bla.jpg\" />"); i can display an image. Here my problem is that the image path is dynamically generated and is in a string variable.
following is the code i tried:
Dim table_builder As New StringBuilder
table_builder.Append("<table width=100%>")
Dim filePath As String = Server.MapPath("../attachments/") & fileName
// file name is the name of the file fetching from the database
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + filePath + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
But it does not show the image through executing the code
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
Server.MapPath("../attachments/") will map the physical path, that's why the image is not showing. so you can edit your code as:
table_builder.Append("<table width=100%>")
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + "../attachments/" & fileName + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
For your reference ,The Answer by splattne says that :
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
Server.MapPath will return the PHYSICAL path of the file on the server. You certainly don't want that as the file will not be accessible from the client side.
You should use relative path
like Dim filePath As String = ("/attachments/") & fileName
with that the file should be accessible from client as
http://domainname.com/attachments/filename
also be careful while using ../ in your paths. You might end up one level lower to your root path and it might not be accessible from client side
Typically ~ can be used to always start the paths from site root

ASP.NET MVC3: Cant find/access file

String DocLocation = System.AppDomain.CurrentDomain.BaseDirectory + "Files/test.pdf";
// or
String DocLocation = Url.Content("~/Files/test.pdf");
var document = new FileStream(DocLocation, FileMode.Open);
var mimeType = "application/pdf";
var fileDownloadName = "download.pdf";
return File(document, mimeType, fileDownloadName);
The first method is UnauthorizedAccessException.
The second method cant find the file.
I am trying to send a file for download. Using full desktop path seems to work.
Also, how would I display PDF in the browser instead (note, still need download option as not all are pdf)?
Try Server.MapPath("~/Files/test.pdf")
File() takes a physical path on disk.
Therefore, you can't use Url.Content, since that returns a relative URL for the browser.
Instead, you need Server.MapPath, which converts an application relative path into a full path on the local disk.

how can get image from a relative path

i am working in asp .net mvc3.
i want to get a image which exist in this location in my project
G:\projects\CalcoWoms\CalcoWOMS\Content\pictures\calcologo.png
CalcoWOMS is my project name. i want to fetch this calcologo.png in following line please check following line and tell me how should write this following line in correct way.?
iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance("~/calcologo.png");
means in place of ("~/calcologo.png"); what path i should write ?
You could use MapPath
var physicalPath = Server.MapPath("~/Content/pictures/calcologo.png");
You could try "%~dp0calcologo.png".
%~dp0 means current directory.
You could use the HostingEnvironment object along with Path.Combine
Path.Combine(#HostingEnvironment.ApplicationPhysicalPath, "calcologo.png");
Of course, #HostingEnvironment.ApplicationPhysicalPath will only take you to the root of your application, so you might need to use "Content/picturescalcologo.png".

Rewrite urls from user submitted HTML

I use one WYSIWYG editor in a small cms. It allows users to upload files, images, etc. If I add image named dog.jpg, in source I'll get:
<img src="/myweb/userfiles/images/dog.jpg" />
I can save this to a database and use it later on any page, until I move my site to a live domain.
myweb is virtual directory in IIS. "/" points to root, in this case localhost, so I have to use "/myweb". However when I upload site to server and copy database there, all links will be broken, because there is no "myweb" folder on server.
My idea was to replace "/myweb" on save with empty string. I also have to replace full url, which editor creates for some files. On display I would have to add correct Application dir. I would probably save both versions in database, and only on server change force display version to update.
By now I've come up with:
p = p.Replace("href=\"" + fullUrl, "href=\"").Replace("src=\"" + fullUrl, "src=\"").Replace("href=\"" + partialUrl, "href=\"").Replace("src=\"" + partialUrl, "src=\"");
Which is ugly, hard to maintain and inefficient. I guess better approach would be to use regex, but I don't know how to do it.
My question is, can anyone recommend good article, blog/forum post on this? If you have other solution, great.
I am unsure the regex version has any of the characteristics you mention in this case.
That said, you can do:
string ReplaceUrlPaths(string html, string partialPath, string fullPath)
{
var pattern = string.Format("((href|src)=\")({0}|{1})", partialPath, fullPath);
var regex = new Regex(pattern);
return regex.Replace(html, m => m.Groups[1].Value);
}
[TestMethod]
public void TestMethod10()
{
var input = #"<img src=""/myweb/userfiles/images/dog.jpg"" />";
//carefull with any special regex char in the paths
var replaced = ReplaceUrlPaths(input, "/myweb", "/some/full/path");
Assert.AreEqual(
#"<img src=""/userfiles/images/dog.jpg"" />",
replaced);
}
If you are proceeding with that, refactor it to instantiate the regex once with the compile option(as the partialPath and fullPath won't be changing).
Also consider avoiding it all, by defining a web site with an alternate port to just have it as a root Url.
Store the local root path separately from the images. For each image, store the relative path to that image.
When displaying images locally, use the local root merged with the relative path. When you publish to the remote server, you add the remote root to the relative path.
Does your WYSIWYG editor allow you to configure the base URL e.g. so that paths to images can use relative paths? I think the FCKEditor has something like FCKConfig.BaseHref in it's config file that does something like this.
Alternatively can you run the site as a root site using the ASP.NET 2.0 web server? Then you wouldn't have to worry about rewriting paths to images as you could just use paths from the webroot.

how can an .ASPX page get its file system path?

I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?
Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:
http://server/path/something.aspx/info1/info2/info3.xml
The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
Request.PhysicalPath
Server.MapPath is among the most used way to do it.
string physicalPath = Server.MapPath(Request.Url);
Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )

Resources