【发布时间】:2021-06-24 02:10:15
【问题描述】:
我想使用 AJAX 调用来渲染图像,但我无法通过 PHP 从服务器将图像作为 base24 字符串返回。
在下面的 renderImage 函数中,测试图像数据“R0lGODlhCw...”显示正确,但来自 AJAX 调用的图像数据不正确。
我想使用 AJAX 而不是仅仅将图像文件内容输出到 src 属性中,因为我最终想将授权标头添加到 PHP 文件中。
我想我在 PHP 文件中遗漏了一些东西,在 ajax 调用中遗漏了一些标头?
PHP 文件:image.php
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
?>
JS
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src","data:image/gif;base64," + res);
} catch(err) {
console.log("error"+err);
}
});
从How to display an image that we received through Ajax call?获取的原始图像
【问题讨论】:
-
你可能会在这里犯错。来自服务器的响应以
'data:image/' . $type . ';base64,'开头,"data:image/gif;base64,"也在客户端的src前面。 -
你也应该在你的 PHP 中
echo $base64;(除非已经有其他代码没有显示) -
在你的
image.php中将这一行$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);return $base64;更改为$base64 = base64_encode($data); echo $base64;然后用你的 ajax 捕获它
标签: javascript php jquery ajax base64