How to display image in web platform stored on server

Akash Gadhave
Akash Gadhave Member
edited October 2 in Q&A #1

I'm using

/v2/content/{id}/download

I'm getting bytes data which is visible in network preview tab, but not able to convert it in some format so that it can be passed to src attribute of image to make it visible on my web application. I have tried many solutions but nothing working.

Best Answer

  • LazarescuA
    LazarescuA E Community Moderator
    #2 Answer ✓

    Hello @Akash Gadhave ,

    In Axios, you need to specify the responseType (otherwise it will default to JSON). You can use responseType arrayBuffer or blob.

    For example, I used responseType: 'blob' in my code, and then with the response (res), I used a reader to set the base64 image like this:

    if (res.data) {
    let reader = new FileReader();

    reader.readAsDataURL(res.data);
    reader.onload = function () {
    const regex = /data:.*base64,/
    imageData = reader.result.replace(regex,""));
    };
    reader.onerror = function (error) {
    console.log(`File reading error: ${error.message}`);
    };
    }

    Then, in the img block, used the imageData:

    <img src={`data:image/png;base64, ${imageData}`} alt='Instance diagram' align="center"/>
    

Answers

  • gvicari
    gvicari E Community Moderator

    Hi @Akash Gadhave, as far as I'm aware it is not possible to directly inject a response from a protected image file (requiring authorization headers) in the src attribute of an image element/component.

    I've quickly looked this up to verify/confirm my understanding and indeed came across the following Stack Overflow post: https://stackoverflow.com/questions/46642960/authorization-header-in-img-src-link

    Did you already see it and tried the different methods (using JavaScript, etc.) they suggest?

  • Yes, I have already tried this,

    Image is visible in network preview tab, but still is not visible on UI.

  • gvicari
    gvicari E Community Moderator

    @Akash Gadhave, I will investigate whether what you see is to be expected and we will get back to you. Cheers.

  • LazarescuA
    LazarescuA E Community Moderator
    #6 Answer ✓

    Hello @Akash Gadhave ,

    In Axios, you need to specify the responseType (otherwise it will default to JSON). You can use responseType arrayBuffer or blob.

    For example, I used responseType: 'blob' in my code, and then with the response (res), I used a reader to set the base64 image like this:

    if (res.data) {
    let reader = new FileReader();

    reader.readAsDataURL(res.data);
    reader.onload = function () {
    const regex = /data:.*base64,/
    imageData = reader.result.replace(regex,""));
    };
    reader.onerror = function (error) {
    console.log(`File reading error: ${error.message}`);
    };
    }

    Then, in the img block, used the imageData:

    <img src={`data:image/png;base64, ${imageData}`} alt='Instance diagram' align="center"/>
    

  • Thanks, that worked.