2

I created a GET route in my back-end server which returns an image, depending on the GET query.

The route is working OK, and looking in the developer tools I can see the image preview correctly as expected - see below:

Image OK in developer tools

When I send this request via Postman, it also works fine and previews the image correctly!

The image data URI gotten via developer tools is a functional and valid URI, as follows:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABkCAYAAADOtM0JAA...

The problem is, when I do an Ajax request to this GET route, and process the result, I'm getting a URI as follows:

data:application/octet-stream;base64,77+9UE5HDQoaCgAAAA1JSERSAAAASwAAAGQIBg...

This 'octet-stream' is not displayable in the browser as an image ( tag ), so it is useless for me.

The code I'm using to process this request in my application is as follows (simplified). Could you help me?

export const userGetProfilePhoto = async () => {

    let ajaxReturn = await $.ajax({
        url: `/getUserPhoto`,
        type: 'get',
        headers: {
        },
        processData: false,
        contentType: false,
        success: function () {
            console.log('userGetProfilePhoto returned success');
        },
        error: function (xhr, status) {
            console.error('userGetProfilePhoto returned error');
        },
        complete: function (xhr, status) {
        }
    });

    let binaryData = [];
    binaryData.push(ajaxReturn);
    let blob = new Blob(binaryData, { type: "" });

    return new Promise((resolve, reject) => {
        var a = new FileReader();
        a.onload = function (e) {
            resolve((e.target.result));
        };
        a.readAsDataURL(blob);

    })
}

1 Answers1

2

Better late than never, here follows a functional jQuery request for this case:



export const userGetProfilePhoto = async (userUID, userToken) => {
    console.debug('userGetProfilePhoto()');

    let ajaxReturn = await $.ajax({
        url: `/storage/getUserPhoto`,
        type: 'get',
        cache: true,
        headers: {  },
        contentType: 'application/json',
        data: { userUID }, //Query specific user picture
        xhrFields: {
            responseType: 'blob' //for arrayBuffer receiving
        },
        success: function () {
            console.log('userGetProfilePhoto returned success');
        },
        error: function (xhr, status) {
            console.error('userGetProfilePhoto returned error');
        },
        complete: function (xhr, status) {
        }
    });

    let blob = new Blob([ajaxReturn], {});

    return new Promise((resolve, reject) => {
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            resolve((e.target.result));
        };
        fileReader.readAsDataURL(blob);
    })
}

Just needed to add 'blob' to xhr responseType.