Weird characters in image response of POST request

2019-08-25 01:07发布

问题:

I've to make POST request to an API and this API returns an image which I want to show on canvas or img element. The problem is weird characters are coming in response but in network tab, image is shown properly(screenshots below)

I've tried everything mentioned in AJAX - Weird characters in img tag after request response

I've tried to convert to base64, load using new Image(), tried to convert to blob, load using FileReader(), but blank image is loaded.

Instead of POST request, if I use some static image URL with new Image() or FileReader(), it works without issues. How do I render an image that comes as a response from POST request? Any help is appreciated.

回答1:

The answer provided by fotinakis in How to parse into base64 string the binary image from response? worked.

While making POST request itself, the responseType has to be set to arraybuffer which can later be converted to base64. Getting base64 from binary was the issue. The success callback of ajax returns binary by default unless set otherwise.

Other responseTypes can be found in https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType.

I still don't understand one thing though. Static image URL(GET) also returns binary data which gives no issues with new Image() but if I pass the same binary data from POST request success callback, it doesn't work.