0

my need is to display an image in a web page using string builder. i know through this snippet sb.Append("<a href=\"http://www.mypage.com\"><img src=\"bla.jpg\" /></a>"); 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()
  • Where do you appent sb (StringBuilder) to table_builder (Stringbuilder)? can you show the generated markup? – Edi G. Sep 02 '14 at 05:51
  • if you see the html generated by above code you will see that filepath is some local path like d:\sitefolder\attachment\filename – Amol Sep 02 '14 at 06:02

2 Answers2

1

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)
Community
  • 1
  • 1
0

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

Amol
  • 838
  • 7
  • 19