0

I want to set an image src in my page with the image i receive from an ajax call response but i get a broken image icon when i set the image src with the reponse.

below is the ajax call

$.ajax({
                        url: '<%=request.getContextPath() %>/rest/tasks/file/'+temp_taskID+'?fileType=JPG' + 
                             '&fileName='+imgNames[i],
                        headers: {
                             'apiKey':'1xxxx3-dde5-4eec-b3ee-2xxxx507xxe8',
                             'ID':ID
                        },
                        type: "GET"
                    })
                    .done  (function(data, textStatus, jqXHR) {
                        $("#img_carousel").attr("src", "data:image/jpeg;base64," + data);                  
                    })
                    .fail  (function(jqXHR, textStatus, errorThrown) {});

error

enter image description here

usr30911
  • 2,731
  • 7
  • 26
  • 56

1 Answers1

1

Found the solution to my issue

https://stackoverflow.com/a/25371174/3518278

had to add mime-type

mimeType: "text/plain; charset=x-user-defined",

and

$("#img_carousel").attr('src', 'data:image/jpeg;base64,' + base64Encode(data));

function base64Encode(str) {
                var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                var out = "", i = 0, len = str.length, c1, c2, c3;
                while (i < len) {
                    c1 = str.charCodeAt(i++) & 0xff;
                    if (i == len) {
                        out += CHARS.charAt(c1 >> 2);
                        out += CHARS.charAt((c1 & 0x3) << 4);
                        out += "==";
                        break;
                    }
                    c2 = str.charCodeAt(i++);
                    if (i == len) {
                        out += CHARS.charAt(c1 >> 2);
                        out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                        out += CHARS.charAt((c2 & 0xF) << 2);
                        out += "=";
                        break;
                    }
                    c3 = str.charCodeAt(i++);
                    out += CHARS.charAt(c1 >> 2);
                    out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                    out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                    out += CHARS.charAt(c3 & 0x3F);
                }
                return out;
            }
Community
  • 1
  • 1
usr30911
  • 2,731
  • 7
  • 26
  • 56