Jump to content
Stuart Clennett

Using an API endpoint as src for img tag ?

Recommended Posts

Hi,

 

Not sure if I'm on the right track here.  I have a legacy database that has some images stored in blob fields in the database (I know).  I'd like to be able to expose these images directly from the REST API, e.g. localhost:8080/rest/default/images/{id} 

 

I guess I have to set the Produces attribute to `image/jpeg` .. but what data type should I return?  I've tried TBytes but although I get the bytes returned in Postman - web browsers don't load the image. 

 

Thanks

Edited by Stuart Clennett

Share this post


Link to post

So I'm back to this.  I'm currently thinking of using Data-URLs to get the base64 image data and embed direcly into the Angular client app.  (ref: https://css-tricks.com/data-uris/ & https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)

 

Note that with the above TBytes solution I seem to get the response "[255, 0, 255, 0, 45, 56, 67 ..... ]"  as text rather than raw bytes.  The end point has the response type set as 'image/jpeg' 

 

 

Edited by Stuart Clennett

Share this post


Link to post

Hi @Stuart Clennett,

you can try using TStream as result type. You can then use a TFileStream (or whatever other TStream descendant).

MARS also has specific support to serve base64 encoded images (look for TStreamWriter class implementation).

 

Let me know if you managed to use it.

 

Sincerely,

Andrea 

Share this post


Link to post

Hi @Andrea Magni

 

I implemented it using a simple base64 encoded string. 

 

Is there any benefit to using TStringWriter given that I may need the API to support web front ends written in a JS framework like Angular ? 

 

Thanks

Share this post


Link to post

As you can see here: https://github.com/andrea-magni/MARS/blob/f3c2396eeac4df9b1f9a4d4ef640d95bb6dd569d/Source/MARS.Core.MessageBodyWriters.pas#L217

It is a really straightforward implementation and I guess yours is not much different. The StreamToBase64 and StringToStream functions are also available just in case you need them.

 

Let me know if there's anything I can help with!

Thanks,

Andrea

  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×