Solved

Display Image from database Table field

Posted on 2011-09-06
9
220 Views
Last Modified: 2012-05-12
I have a database query that returns a data with a field to the image file location (see attached).
The image file location is on another machine. I have been struggling to get the aspx page display the image.
Can anyone please tell me how to go about this?

imagefromDB.doc
0
Comment
Question by:olootu
  • 5
  • 3
9 Comments
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 36488304
You must first check the user who is running the ASP.net process. Normally this is NETWORK SERVICE, but it depends on the IIS and ASP.Net version.

Once you know the user who is running the process, you must ensure to give that user at least read permissions for the folders and files in which the images are stored.

Hope that helps.
0
 
LVL 18

Accepted Solution

by:
ivan_vagunin earned 250 total points
ID: 36488365
To display image on the webpage it should be available via HTTP protocol (just shared folder is not enough). This means you either run HTTP server on machine where the pictures are located, or create a http handler which will read file from shared folder and return its stream via HTTP protocol.
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36488433
Indeed IE (don't know for others) can use file:// protocol to read local and shared files (client should have permissions for shared file), but it is not natural for web applications , so I think the best solution is to create HTTP handler.
Hope that helps.
0
 

Author Comment

by:olootu
ID: 36488563
How do I create a 'HTTP Handler'? Any link that could help?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36488596
0
 

Author Comment

by:olootu
ID: 36488786
Talking about HttpHandler, I found this code in one of the files. Could this be something similar?
(I did not mention earlier that I was converting a asp pages to .Net)


<%@Import Namespace="System.Drawing.Imaging" %>
<%@Import Namespace = "System.Web" %>
<%@Import Namespace = "System.Web.Security" %>
<%@Import Namespace = "System.Security.Principal" %>
<%@Import Namespace = "System.Runtime.InteropServices" %>

<script language="VB" runat="server">

 ' -----------------------------------------------------------------------------------------
 ' Declare variables and Windows libraries for impersonating
 ' canterbury\dmzspur
 '
 Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
 Dim LOGON32_PROVIDER_DEFAULT As Integer = 0

 Dim impersonationContext As WindowsImpersonationContext

 Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, _
                        ByVal lpszDomain As String, _
                        ByVal lpszPassword As String, _
                        ByVal dwLogonType As Integer, _
                        ByVal dwLogonProvider As Integer, _
                        ByRef phToken As IntPtr) As Integer
"
 Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
                        ByVal ExistingTokenHandle As IntPtr, _
                        ByVal ImpersonationLevel As Integer, _
                        ByRef DuplicateTokenHandle As IntPtr) As Integer

 Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
 Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long

 '
 ' Declartions for impersonation completed.
 ' -----------------------------------------------------------------------------------------

  Function ThumbnailCallback() as Boolean
    Return False
  End Function


  
  Sub Page_Load(sender as Object, e as EventArgs)
  

 try

    '
    ' Get settings from web.config
    '
            Dim spurUser As String = ConfigurationSettings.AppSettings("takenoffforsecurity")
            Dim spurUserPassword As String = ConfigurationSettings.AppSettings("takenoffforsecurity")
            Dim spurDomain As String = ConfigurationSettings.AppSettings("takenoffforsecurity ")
            Dim spurFolder As String = ConfigurationSettings.AppSettings("takenoffforsecurity")
    '
    ' Read in the image filename to create a thumbnail of
    '
    Dim film as String = Request.QueryString ("film")
    Dim photo as String = Request.QueryString ("photo")
    
    'Make sure that the image URL doesn't contain any /'s or \'s
    If film.IndexOf("/") >= 0 Or film.IndexOf("\") >= 0 then
      Response.End()
    End If
    if photo.indexof ("/") >= 0 or photo.indexof ("\") >= 0 then
      response.end ()
    end if
    
    '
    ' Create the full path to the image.
    '
    dim imageUrl as String = spurFolder & film & "\" & photo & ".jpg"
    
    '
    ' Try to impersonate the spur user with privileges to the images.
    '
    If impersonateValidUser(spurUser, spurDomain, spurUserPassword) Then
        
    	' Get the image.  
        '    
	 Dim fullSizeImg as System.Drawing.Image = System.Drawing.Image.FromFile(imageUrl)
    
    	' Resize the image.
        '
	Dim dummyCallBack as System.Drawing.Image.GetThumbNailImageAbort = New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
    
        Dim resizedImg as System.Drawing.Image = fullSizeImg.GetThumbnailImage (99, 75, dummyCallback, IntPtr.Zero)
        resizedImg.Save(Response.OutputStream, ImageFormat.Jpeg)

   	Response.ContentType = "image/jpeg"    
    	resizedImg.Save(Response.OutputStream, ImageFormat.Jpeg)
    
        '
    	'Dispose/clean up...
        '
    	fullSizeImg.Dispose()
    	resizedImg.Dispose()
        '
        ' Stop impersonating the spur user.
        '
    	undoImpersonation()
    Else
	Response.ContentType = "text/xml"
        Response.Write("Authentication failed")
    End If


catch ex As Exception
	Response.Write("Error: " & ex.Message)
	
End Try
    
  End Sub


Function impersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean

    Dim tempWindowsIdentity As WindowsIdentity
    Dim token As IntPtr = IntPtr.Zero
    Dim tokenDuplicate As IntPtr = IntPtr.Zero
    impersonateValidUser = False

    If RevertToSelf() Then
        If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
            If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
                tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
                impersonationContext = tempWindowsIdentity.Impersonate()
                If Not impersonationContext Is Nothing Then
                    impersonateValidUser = True
                End If
            End If
        End If
    End If
    If Not tokenDuplicate.Equals(IntPtr.Zero) Then
        CloseHandle(tokenDuplicate)
    End If
    If Not token.Equals(IntPtr.Zero) Then
        CloseHandle(token)
    End If
End Function



Sub undoImpersonation()
    impersonationContext.Undo()
End Sub



</script>

Open in new window

0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36489538
Yes, this is something similar - it is not a http handler, but page that acts the same way - when it is requested, it reads file from some folder and returns picture stream instead of html. You can use it like this:
<img src="page.aspx?film=SomeFilm&photo=Photo1.jpeg"/>
0
 

Author Comment

by:olootu
ID: 36489970
You're right. Below is line of code from one one the script that I am converting.
The line that is confusing me is this:
<img src='344px/" & url & "'></a>") .

The file I believe that it is refering to is named 'image344.aspx. I don't understand while it is called 344px in the img src


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>Parking fine payment</title>
    <!--#include file="ADOConn.asp" -->
    <!--#include file="CGI.asp" -->
    <!--#include file="HTML.asp" -->
	</head>
  <body>
    <h1>Parking fine payment</h1>
    <%
    
      Rem Original code (c) Spur Information Systems.
      Rem 01/04/08: aiwg: Rewritten to fix SQL injection attack risk
      
      pcn = cgi_param ("pcn")
      vrm = cgi_param ("vrm")
      
      if pcn <> "" and vrm <> "" then
      
        vrm = replace (vrm, " ", "")
      
    		strSQL = "SELECT dbo.Cases.FormattedCaseNo, dbo.SPID_Item.DescriptionShort, "
    		strSQL = strSQL & " dbo.Cases.CaseDate, dbo.Cases.VehicleMake, dbo.Cases.IssueTime, "
    		strSQL = strSQL & " dbo.Cases.VRM, dbo.OffenceCodes.OffenceLongDesc, "
    		strSQL = strSQL & " dbo.Cases.CaseID, dbo.Cases.CurrentStateCode, "
  	 	  strSQL = strSQL & " (dbo.Cases.CaseCurrentOutstandingAmount - ISNULL((SELECT SUM(value) FROM CobaltWebPayments WHERE refno='" & cgi_sqlencode (pcn) & "'),0)) as CaseCurrentOutstandingAmount"
    		strSQL = strSQL & " FROM dbo.Cases LEFT OUTER JOIN "
    		strSQL = strSQL & " dbo.OffenceCodes ON dbo.Cases.CaseOffenceID = dbo.OffenceCodes.OffenceID "
    		strSQL = strSQL & " LEFT OUTER JOIN dbo.SPID_Item ON "
    		strSQL = strSQL & " dbo.Cases.StreetCarParkSpidID = dbo.SPID_Item.SPIDID"
    		strSQL = strSQL & " WHERE FormattedCaseNo = '" & cgi_sqlencode (pcn) & "'"
    		strSQL = strSQL & " AND VRM = '" & cgi_sqlencode (vrm) & "'"
    		
    		set recCases = Server.CreateObject("ADODB.Recordset")
    		recCases.ActiveConnection = conn
    		recCases.Open strSQL
        
    		if recCases.EOF and recCases.BOF then
    		  response.write ("<h2>Ticket not found</h2>")
    		  response.write ("<p>Please check you've entered the PCN number and registration number correctly.</p>")
    		else
    		  recCases.MoveFirst
    		  pcn = recCases.fields ("FormattedCaseNo")
    		  vrm = recCases.fields ("VRM")
    		  response.write ("<h2>" & cgi_htmlencode (pcn) & "</h2>")
    		  if left (recCases.fields ("CurrentStateCode"), 3) = "BAL" then
    		    paymentURL = ""
    		    paymentError = "This PCN has been passed to our Bailiffs. Please refer to them for further instructions on making a payment. You should have received a notification by post with details on how to make a payment to the Bailiff. If this is not the case please contact contact us."
    		  else
      		  if recCases.fields ("CaseCurrentOutstandingAmount") > 0 then
      		    paymentURL = "http://www.mycompany/pay.php?pcn=" & cgi_urlencode (pcn) & "&vrm=" & cgi_urlencode (vrm) & "&amt=" & cgi_urlencode (recCases.fields ("CaseCurrentOutstandingAmount") * 100)
      		  else
    	  	    paymentURL = ""
    	  	    paymentError = "This case is closed"
    		    end if
    		  end if
    		  response.write ("<ul class='right'>")
    		  if paymentURL <> "" then
    		    response.write ("<li><a href='" & cgi_htmlencode (paymentURL) & "'>Make payment</a></li>")
    		    response.write ("<li><a href='" & cgi_htmlencode ("contact.asp?pcn=" & cgi_urlencode (pcn) & "&vrm=" & cgi_urlencode (vrm)) & "'>Contact us</a></li>")
    		  end if
    		  
    		  if paymentURL <> "" then
    		  
        		strSQLImages = "SELECT dbo.Digital_Camera_Images.DCImgID, "
        		strSQLImages = strSQLImages & " dbo.Digital_Camera_Images.RelatedFilmID "
        		strSQLImages = strSQLImages & " FROM dbo.Digital_Camera_Images RIGHT OUTER JOIN "
        		strSQLImages = strSQLImages & " dbo.Cases ON dbo.Digital_Camera_Images.RelatedCaseID = dbo.Cases.CaseID "
        		strSQLImages = strSQLImages & " WHERE (dbo.Digital_Camera_Images.DCImgID IS NOT NULL) "
        		strSQLImages = strSQLImages & " AND dbo.Cases.CaseID = " & recCases.fields("CaseID")
      		
        		set recImages = Server.CreateObject("ADODB.Recordset")
        		recImages.Open strSQLImages, conn,1
          
        		if recImages.BOF and recImages.EOF then
        			gblnImages = 0
        		else
        			gblnImages = 1
        			set rsPicsPath = Server.CreateObject("ADODB.Recordset")
        			rsPicsPath.ActiveConnection = conn
        			strSQL = "SELECT GSDSetting from GSD where GSDCode = 'FILE_LOC_DIGITALPHOTOS'"
        			rsPicsPath.Open strSQL
        			rsPicsPath.MoveFirst
        			if not rsPicsPath.BOF and not rsPicsPath.EOF then
        				strPicsPath = rsPicsPath.Fields("GSDSetting")
        			else
        				Rem pics path not found so turn them off
        				gblnImages = 0
        			end if
        		end if
    		  
        		if gblnImages = 1 then
        			intLocationCounter=1
        			recImages.MoveFirst
        			do until recImages.EOF
        				strPadPicName=""
        				For intCounter = 1 to 16 - len(recImages.fields("DCImgID"))
        					strPadPicName = strPadPicName & "0"
        				next
        				strPadPicName = strPadPicName & recImages.fields("DCImgID") & ".jpg"							
        				Response.Write("<li><a href='" & cgi_htmlencode ("details.asp?vrm=" & cgi_urlencode (recCases.fields("VRM")) & "&PCN=" & cgi_urlencode (pcn) & "&autopic=" & intLocationCounter) & "'><IMG src='99px/" & recImages.fields("RelatedFilmID") & "/" & strPadPicName & "' alt='Thumbnail photograph - click to see larger image'></a></li>")
        				intLocationCounter = intLocationCounter + 1
        				recImages.moveNext
        			loop
        		end if
        	
        	else
        	  gblnImages = 0        	
          end if
	
	        response.write ("</ul>")
	        html_table ()
            html_tr ()
              html_th ("PCN number")
              html_td (cgi_htmlencode (pcn))
            html_tr ()
              html_th ("Vehicle registration")
              html_td (cgi_htmlencode (vrm))
            html_tr ()
              html_th ("Vehicle make")
              html_td (cgi_htmlencode (recCases.fields ("VehicleMake")))
            html_tr ()
              html_th ("Contravention date and time")
              html_td (cgi_htmlencode (FormatDateTime (recCases.fields ("CaseDate"), 1)) & " " & recCases.fields ("IssueTime"))
            html_tr ()
              html_th ("Location")
              html_td (cgi_htmlencode (recCases.fields ("DescriptionShort")))
            html_tr ()
              html_th ("Contravention")
              html_td (cgi_htmlencode (recCases.fields ("OffenceLongDesc")))
            html_tr ()
              html_th ("Outstanding amount")
              if paymentURL = "" then
                html_td (paymentError)
              else
                html_td ("<a href='" & cgi_htmlencode (paymentURL) & "'>&pound;" & recCases.fields ("CaseCurrentOutstandingAmount") & "</a>")
              end if
  	      html_etable ()
  	      
  	      if paymentURL <> "" then
    	      response.write ("<p>")
    	      if gblnImages = 0 then
    	        response.write ("No images are available")
    	      else
    	        recImages.MoveFirst
    	        strPadPicName = ""
    	        for intCounter = 1 to 16 - len (recImages.fields ("DCImgID"))
    	          strPadPicName = strPadPicName & "0"
    	        next
    	        if cgi_param ("autopic") <> "" then
    	          recImages.Move (int (cgi_param ("autopic")) - 1)
    	        end if
    	        strPadPicName = strPadPicName & recImages.fields ("DCImgID") & ".jpg"
    	        url = cgi_htmlencode (recImages.fields ("RelatedFilmID") & "/" & strPadPicName)
    	        response.write ("<a href='pics/" & url & "' target=_blank title='View in a new window'><img src='344px/" & url & "'></a>")
    	      end if
    	      response.write ("</p>")
    	    end if

  	      response.write ("<hr>")
    		  
    		end if
    	
    	else
    	  if pcn <>"" or vrm <> "" then
      	  response.write ("<p><strong>Please enter both the PCN number and registration number</strong>.</p>")
      	end if
  		end if
    %>
    
    <h2>Ticket details</h2>
    
    <form method="post" action="details.asp">
    <%
      html_table ()
        html_tr ()
          html_th ("PCN number<br>E.g. CT12345678")
          html_td ("<input name='pcn' type='text' class='textbox' value='" & cgi_htmlencode (pcn) & "' onfocus='select()' style='text-transform:uppercase'>")
        html_tr ()
          html_th ("Vehicle registration number")
          html_td ("<input name='vrm' type='text' class='textbox' value='" & cgi_htmlencode (vrm) & "' onfocus='select()' style='text-transform:uppercase'>")
        html_tr ()
          html_th ("&nbsp;")
          html_td ("<input type='submit' name='action' value='Lookup PCN'>")
      html_etable ()
    %>
    </form>

  </body>
</html>

Open in new window

0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36490876
I guess 344px is a name of some site folder, where image344.aspx is located.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This video discusses moving either the default database or any database to a new volume.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now