Returning something other than HTML

Is it possible to set up an Aurelia route that returns (for example) an image?

My use case is this: I want to make it super easy to display a profile photo from MS graph. The http call to fetch a photo needs to have an authorization header so I can’t just use <img src="...">, so right now I’m fetching the image in the view model, converting it to Base64 and binding to it from the view.

I was thinking it’d be cool to be able to do something like <img src="/photo/${id}"> and handle the “/photo” route myself in Aurelia, returning image/jpeg rather than HTML.

Can a route return something other than HTML?

1 Like

for <img src="/photo/${id}">, it’s a normal binding that is not in the realm of the router at all. But maybe you can have a value converter to connect this and a router? It may look like this:

<img src.bind="`/photo/:id` | route: myRouter">

But ultimately the src attribute has to be a URL, and that URL has to return the bytes of the image. Anything I bind to the src attribute, even through a value converter, has to be a URL, right?

My thinking was to set up a route in the app (say /photo/:id) which returned an image rather than HTML. So then I can just set the src attribute to that (eg src="/photo/${id}"). Not binding per se.

I have a workaround (a “user-photo” template that does the hard work in the viewmodel) that I’m happy with, but I thought this might’ve been a cooler solution.

1 Like

This could be an extra usecase of either the router, or just the binding system. Looks pretty interesting for router.

1 Like

The approach feels bit odd to me. Ideally the endpoint returning the bytes should set the correct mime-type and if you bind the endpoint url to the <img src="image-endpoint"> it should display the image. It should be that simple.

EDIT: Sorry I missed the header part

1 Like

Have you tried a custom protocol for this?

I’ve had a very similar use case, where I had a dynamic URL that pointed to a protected API that returned the image. The solution I came up with was a custom attribute that translated the URL into a Data URL by making the API call in the background (with the authorization header). The usage for something like:

<img api-src="${url}" />

An additional benefit was that the request was done in the background, and the custom attribute could show a loading animation while the image was being loaded.

5 Likes

Ah! That makes sense! I imagine you could even set the “title” attribute of the image along with the “src” attribute that way (e.g. if the API returned a description as well as an image). That’s a great solution!

2 Likes