Search code examples
javascriptjsfurl-encodinggraphicimage

Prevent JSF encoding of & as & in image url


I'm getting an image url from my database and need to display it in an <img> tag. The problem I have is that JSF is encoding &'s as &amp; and the image url is not found.

Here's an example. The correct image url:

https://<server details>?ahid=2096&aid=107687&lid=28812968&url=202.jpg

The encoded url:

https://<server details>?ahid=2096&amp;aid=107687&amp;lid=28812968&amp;url=202.jpg

In this case the encoded image url is not found and displays the broken image icon. How do I solve this?

EDIT: the html elements with their JSF tags:

<a href='#{product.itemUrl}' target="_blank"> 
    <img src='#{searchResults.getThumbnailUrl(product)}' class="img-responsive imageproduct" />
</a>

EDIT 2:

I thought I'd try replacing the &amp; back to & with javascript but this doesn't work either because in the javascript the image url is fine, while in the browser's view source it's not. Here's the code. In the browser:

<img id="thumbnailId" onmouseover="decodeUrl(this)" src="https://www.proxibid.com/asp/LotImageViewer.asp?ahid=3231&amp;aid=108183&amp;lid=28955872&amp;url=144-1.jpg" />

The javascript:

function decodeUrl(img) {
    var url = img.src;
    console.log("url before = " + url);
    url = replaceAll(url, "&amp;", "&");
    console.log("url after = " + url);
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

The output is

url before = https://www.proxibid.com/asp/LotImageViewer.asp?ahid=3231&aid=108183&lid=28955872&url=144-1.jpg
url after =  https://www.proxibid.com/asp/LotImageViewer.asp?ahid=3231&aid=108183&lid=28955872&url=144-1.jpg

as you can see the two are identical, and correct. But doing a view source results in

src="https://www.proxibid.com/asp/LotImageViewer.asp?ahid=3231&amp;aid=108183&amp;lid=28955872&amp;url=144-1.jpg"

which is incorrect, and the image is broken. Any idea how to fix this?


Solution

  • What you see in your browser is correct. In html an & should be encoded as &amp; This is technically interpreted as an & when your browser is requesting the image as you can see what you post in the comment as an http 200 response. What is wrong here is that you expect https://www.proxibid.com/asp/LotImageViewer.asp?ahid=3231&amp;aid=108183&amp;lid=28955872&amp;url=144-1.jpg to return an image when it returns an html page

    LotImageViewer.asp?ahid=4292&aid=108223&lid=29012930&url=127.jpg
    www.proxibid.com/asp
    GET 200 OK
    text/html
    searchresults:696 Parser 5.1 KB 34.7 KB 277 ms 228 m 
    

    If you post this url in your browser (or just click here) you can see what it returns. So basically, the error is your 'expectation'. If you click the 'full screen' in the image, you'll see

    https://www.proxibid.com/AuctionImages/3231/108183/FullSize/144-1.jpg
    

    Which shows the image full screen. So You need to adapt your code