【问题标题】:Using an AJAX call to display base64 image data via PHP使用 AJAX 调用通过 PHP 显示 base64 图像数据
【发布时间】: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


【解决方案1】:

首先你应该修复你的 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);
echo json_encode(array('id' => $base64));
?>

然后是你的javascript,因为你已经定义了数据图像类型,所以不需要在javascript上重复它。

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", res);
  } catch(err) {
    console.log("error"+err);
  }
});

【讨论】:

  • 这是一个很好的解决方案。我只需要从 echo 调用中删除 json 编码 -> echo $base64; 就可以了。谢谢!
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
相关资源
最近更新 更多