0

I'm trying to convert the response of the dropbox get_thumbnail api to an actual img tag in my page, actually the response returned from the api has a shape like the following

����JFIF��C %# , #&')*)-0-(0%()(��C (((((((((((((((((((((((((((((((((((((((((((((((((((��@0"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�

This is what I've tried to convert that response in an img element:

var imgsrc = 'data:image/jpeg;base64,' + hexToBase64(data);
var img = new Image(100, 100);
img.src = imgsrc;
document.body.appendChild(img);

function hexToBase64(str) {
   return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

Where the data variable passed to the hexToBase64 function contain the server response but it did not work (this solution is just a copy-paste of code retrieved in another stackoverflow question).

Any help is very appreciated.

Thanks.

Brakko
  • 43
  • 1
  • 7
  • [Cross-linking for reference: https://www.dropboxforum.com/t5/API-support/How-use-get-thumbails-response/m-p/213351/highlight/true#M10843 ] – Greg Mar 27 '17 at 01:10
  • @Greg yep! mattia o. it's always me :) today I will try the solution proposed by them. thanks! – Brakko Mar 27 '17 at 07:38

1 Answers1

0

I too had this same issue with many question marks showing up in the JFIF content-download returned from get_thumbnail API. I'm curious how it would work with DataURI but I was able to convert the returned JPEG/JFIF into an img tag by first converting it into a "blob" like below AND setting overrideMimeType to the "text/plain"

    const Http = new XMLHttpRequest();
    const url = 'https://content.dropboxapi.com/2/files/get_thumbnail_v2';

    //make sure that all text stays as plain text when read in...
    Http.overrideMimeType('text/plain; charset=x-user-defined');

    Http.open("POST", url);

    Http.responseType = "blob";
    
    Http.setRequestHeader('Authorization', 'Bearer ' + access_token_dropbox);

    Http.setRequestHeader('Dropbox-API-Arg', JSON.stringify(data));

    Http.send();

    Http.onreadystatechange = (e) => {

        if (Http.readyState === 4) {
            let jpegData = Http.response;

            var imageUrl = URL.createObjectURL(Http.response);

            document.getElementById("firstDiv").innerHTML = `<img src="${imageUrl}" alt="jo mama" />`;
    }}

I got this idea from another question posed here that had a similar issue and was resolved by changing xmlhttprequest.responseType to "blob"

Sman664
  • 1
  • 1