简体   繁体   English

使用 AJAX 调用通过 PHP 显示 base64 图像数据

[英]Using an AJAX call to display base64 image data via PHP

I'm wanting to render an image using an AJAX call but I'm having trouble returning an image from the server as a base24 string via PHP.我想使用 AJAX 调用渲染图像,但我无法通过 PHP 从服务器以 base24 字符串形式返回图像。

In the renderImage function below the test image data 'R0lGODlhCw...' is displaying correctly but the image data coming from the AJAX call is not.在下面的 renderImage 函数中,测试图像数据“R0lGODlhCw...”显示正确,但来自 AJAX 调用的图像数据显示不正确。

I want to use AJAX instead of just outputting the image file contents into the src attribute because I eventually want to add authorization headers to the PHP file.我想使用 AJAX 而不是仅仅将图像文件内容输出到 src 属性中,因为我最终想向 PHP 文件添加授权标头。

I think I'm missing something in the PHP file and some headers in the ajax call?我想我遗漏了 PHP 文件中的某些内容和 ajax 调用中的一些标题?

PHP file: image.php 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 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);
  }
});

raw image obtained from How to display an image that we received through Ajax call?如何显示我们通过 Ajax 调用收到的图像获得的原始图像

First you should fix your php image rendering首先你应该修复你的 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));
?>

Then your javascript, as you already defined the data image type there is no need to repeat it on the javascript.然后你的 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);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM