POST 请求的图像响应中的奇怪字符

2022-01-17 00:00:00 image jquery ajax html5-canvas

我必须向 API 发出 POST 请求,该 API 返回一个我想在画布或 img 元素上显示的图像.问题是奇怪的字符正在响应,但在网络选项卡中,图像显示正确(下面的屏幕截图)

我已经尝试了

如果我使用带有 new Image()FileReader() 的静态图像 URL 而不是 POST 请求,它可以正常工作.如何渲染来自 POST 请求的响应的图像?任何帮助表示赞赏.

解决方案

fotinakis 提供的答案-parse-into-base64-string-the-binary-image-from-response">如何将响应中的二进制图像解析为base64字符串?成功了.

在自己发出 POST 请求时,responseType 必须设置为 arraybuffer,稍后可以将其转换为 base64.从二进制文件中获取 base64 是问题所在.ajax 的成功回调默认返回二进制,除非另有设置.

其他 responseType 可以在 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType.

我还是不明白一件事.静态图像 URL(GET) 还返回二进制数据,这对 new Image() 没有任何问题,但如果我从 POST 请求成功回调中传递相同的二进制数据,它就不起作用.

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.

解决方案

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.

相关文章