Alex Alex - 2 months ago 22
TypeScript Question

Displaying raw JPEG in html/js

I'm getting an image that is in this format:

����JFIF``��C

$.' ",#(7),01444'9=82<.342��C

2!!22222222222222222222222222222222222222222222222222���|"��
���}!1AQa"q2���#B��R��$3br�
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
���w!1AQaq"2�B���� #3R�br�
$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������?�4���)����4�㊎D,>W�}jLsIބ�Y~{鑻a��6�ҙb�'��I�Fj�+��K�R
�dhr=���4�������+R~S���Zq�>�g �5Vղ_��[�y��(,�����Ґ2�$?Z@(��K��I�|Ro��G#қ��K�Ґ��pM7|7w��I���Q@��)��J��jIeo��?�篵Z�����9��8�a����[W%�r��F2E4Es�e��/������]��i�92�Pf���݃yo��O��n���9f�]�;W�=zRt��綃ނ*}Z{ׂ�P!�̤�YEt�s�!���s���zR�EQdP�]\��b�@̫����Q������d��k��t�&�Nk�L��@f�&�>Ê�u�����������`���-�s�/ ���ʪF�p)�f�c�(aLd?p�I�I��7Rr=h��i����2=�2�4���P��'�3擨*����%ߖ�*]��`Q�ڌ�&G�+��5䈹E��Mu2F����E���jϔp�����_�qp����^�V������^�ː���̬b�'l�E/��'漛��


Although normally chrome detects the image and shows a preview in the developer panel, it doesn't manage that. The response headers are this which should the the browser that this is an image:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:3333
Cache-Control:private
Content-Length:2621
Content-Type:image/jpeg
Date:Wed, 05 Oct 2016 12:43:00 GMT
Server:Microsoft-IIS/8.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET


Here is my photo request method in typescript:

private photoHttpRequest(userId: string): Promise<string> {
const photoRequest: XMLHttpRequest = new XMLHttpRequest();
const url: string = "some url" + userId;
photoRequest.open("GET", url, true);

return new Promise((resolve, reject) => {
photoRequest.onreadystatechange = () => {
if (photoRequest.readyState === 4) {
if (photoRequest.status === 200) {
resolve(photoRequest.responseText);
} else {
reject(photoRequest.responseText);
}
}
};

photoRequest.send("");
});
}
}


And after this, i just convert to base64:

let photo: string = await this.photoHttpRequest("1234");
photo = "data:image/*;base64,"+window.btoa(encodeURIComponent(photo));


And pass it in to a
img.src
but that doesn't work.

What am i doing wrong?

Answer

Set the response to be a blob

You have two methods

  • set xhr's responseType to "blob"
  • use fetch fetch(url).then(res => res.blob()).then(blob => console.log(blob))

Then use img.src = URL.createObjectURL(blob) and do what you want with it


Best would be if you didn't need ajax at all since it looks like you are doing a simple GET request