Reputation: 693
i'm building a web application that send some information to an API (API Gateway of AWS) and it receive back an image and some informations (strings) about that image. The strings and the image are generated by a lambda function (AWS service) written in python.
The idea is to have a simple html page where I enter information, press a button and after processing in the cloud I am shown an image and some information. The management of the json received by the API gateway is done in javascript.
I already have the code for the management of the html page, it is already tested and it works, I show it for completeness:
function getImageFromLink(){
return fetch("https://cors-anywhere.herokuapp.com/http://media.gta-series.com/images/gta2/maps/downtown.jpg");
}
async function buttonClick2(){
const returned = await getImageFromLink();
console.log(returned);
let immagine = await returned.blob();
outside = URL.createObjectURL(immagine);
document.getElementById("image").src = outside;
Now, i wanted to do it returning a json: all kyes have strings as values except for one that is for the image.
How can i do that? I mean: how can i put the image into the json in python (in the lambda function)? And how do i have to handle this json in javascript?
Upvotes: 0
Views: 638
Reputation: 1406
Option 1 (Recommended and easy)
Send url
of image instead of sending the whole blob of image in your API response. the url can be a cloud location. This is recommended way.
Option 2 (For your case)
Convert your image into Base64
encoding in Python using base64
library and send it as a part of your json response.
{'image': '<your base64 encoded>'}
And decode the base64 string on JS side:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
Option 3 (Bit tricky and not preferred)
Here you can send the image as FormData, as multipart/form-data, which is not a great way to do. Refer to his on how to achive it - https://julien.danjou.info/handling-multipart-form-data-python/
Upvotes: 1