简体   繁体   中英

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.

In the renderImage function below the test image data 'R0lGODlhCw...' is displaying correctly but the image data coming from the AJAX call is not.

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.

I think I'm missing something in the PHP file and some headers in the ajax call?

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

raw image obtained from How to display an image that we received through Ajax call?

First you should fix your php image rendering

<?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.

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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