In my project, there is a URL that normally responses an image with Content-Type:image/png
that drawn by Java dynamically with user's data.
But sometime causes some reason, the user should not see the image or the image cannot be drawn with user's data. In this case, server will response JSON result that contains error info with
Content-Type:application/json; charset=utf-8
Is this possible to show the image while server response Content-Type:image/png
otherwise to alert error info while Server response Content-Type:application/json; charset=utf-8
?
I can handle either of the response content type, but struggling with handling both of two content type in one request. is this possible?
EDIT
I tried using AJAX like
<img id="preview-img"/>
$.ajax({
url: "/preview",
type: "GET",
dataType: "JSON",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
With above code, alert(data.msg)
is available when Server response a JSON result with error message, but alert("occur error")
will triggered when Server response correct Image.
And I retried with remove dataType
:
$.ajax({
url: "/preview",
type: "GET",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
Glad to see the success
function is triggered whether Server response Image or JSON
But I don't know how to display Image with response data that looks like
ÿØÿàJFIFÿÛC
$.' ",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀ%a"ÿÄ
ÿĵ}!1AQa"q2¡#B±ÁRÑð$3br
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿĵw!1AQaq"2B¡±Á #3RðbrÑ
$4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚâãäåæçèéêòóôõö÷øùúÿÚ?÷ú(¢
......
A bunch of garbage.
And now I temporarily not to handle JSON result
<img id="preview-img"/>
var image = new Image();
image.onload = function () {
$("#preview-img").attr("src", "/preview");
};
image.onerror = function() {
alert("could not load image");
};
image.src = "/preview";