Slevunio
Slevunio

Reputation: 41

How can I display image by href tag pointing to REST api?

I'm building some web app. On my frontend side I need to display images which are earlier uploaded to spring-boot hsqldb. Image data is stored as a BLOB type in database. I want to display them as:

<img href="/api/photos/0">

In the past I was sending GET request to my api to get image data as byte array, than encoding it to Base64, sending back as a string "data:image/jpg;base64, myData" and putting it to img src and it worked perfectly. Now I want to check some different approach and I got stuck.

This is my vue template:

<div class="card">
   <div class="card-header"><h4>Some header</h4></div>
   <div class="card-body">
       <img class="card-img-top" :href="url">
   </div>
</div>

This is my vue method building url:

    export default {
        data(){
            return{
                url:''
            }
        },
        mounted() {
            this.makeUrl();
        },
        methods:{
            makeUrl(){
                this.url="/api/photos/0";
            }
        }
    }

And this is my spring-boot api controller:

    @GetMapping(value = "/photos/{id}")
    public String readPhoto(@PathVariable Long id){
        return makePhotoUrl(photosRepository.findById(id).get().getData());
    }

    private String makePhotoUrl(byte[] photo){
        String photoUrl = "data:image/jpeg;base64," + 
        Base64.getEncoder().encodeToString(photo);
        return photoUrl;
    }

I do get image data by accessing url directly by a browser, but my card is still empty.

Please help because i have no more ideas how to make it work.

Upvotes: 2

Views: 2457

Answers (1)

Slevunio
Slevunio

Reputation: 41

So, after another day of research I've finally figured it out. Basically I've made two mistakes. First, href specifies link destination, but it should be used only with "a" tag:

<a href = "www.someWebsite.com">link</a>

If i want to specify img source I should use "src":

<img src = "www.someOtherWebsite.com">

Second, it appears that if I want to return url as a direct response from api, it must point to a physical file. I might be wrong, so please correct me. I've changed my controller to:

    public ResponseEntity<Resource> readPhotoById(Long id) {
        Photo photo = photosRepository.findById(id).get();
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(photo.getType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + photo.getName() + "\"")
                .body(new ByteArrayResource(photo.getData()));
    }

Now it works as expected.

Cheers :)

Upvotes: 2

Related Questions