File object (image) as value in a dictionary python - javascript

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?

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/

Related

Is there a way to get Attachments url from Microsoft Graph Subscription response?

I'm trying to include Microsoft Graph API mail subscription in a Javascript project with #microsoft/microsoft-graph-client, I get an object response (body, subject, cc, to ...etc) and a Boolean hasAttachments: true but the attachment url is nowhere to be found, is there a way to get these attachments ?
when you got the message
try this url
GET /me/messages/{id}/attachments/{id}
Ok i tried this Graph API call using Javascript code and it's working for me (get the .txt file):
const options = { authProvider, };
const client = Client.init(options);
let res = await client.api('/me/messages/AAMkAGRlNWM4Njk4LWY3NTYtNGE2MC05ZjQzLTg1YmM5YjIzNTRhMwBGAAAAAAA-L78mmzKFQ7FpvCcWkAziBwCUgufVfU8cSKxkYzIkrl81AAAAAAEMAACUgufVfU8cSKxkYzIkrl81AACABFjMAAA=/attachments/AAMkAGRlNWM4Njk4LWY3NTYtNGE2MC05ZjQzLTg1YmM5YjIzNTRhMwBGAAAAAAA-L78mmzKFQ7FpvCcWkAziBwCUgufVfU8cSKxkYzIkrl81AAAAAAEMAACUgufVfU8cSKxkYzIkrl81AACABFjMAAABEgAQAHhM4mZxBRNBqkVbYUzUcWA=').get();
and to convert the contentbytes and store it locally refer the related link - download attachments from mail using microsoft graph rest api as well.

How can I save a string to a textfile in Cloud Storage, in an angular app?

Here is my problem:
I'm writing an angular app, I use App Engine and Google Cloud Storage as the backend (JAVA 8). Now I have text, and I want to save it to my database. Using cloud storage I need this text to be saved as a file. One manner to do that would be to convert my string into a file Object and send it to server via a multipart request.
How can I do that?
Here is my code so far (the aim of that code is to send a photo plus a text description):
uploadAlbum(index:number){
const formData = new FormData();
//`myPhoto` is a file created with the <input type="file"> tag
formData.append('file', myPhoto, '/gcs/my-bucket/' + index +'/cover/cover.jpg');
//here is my problem here `description` is not a file
formData.append('description', description, '/gcs/my-bucket/' + index +'/cover/cover.txt');
this.http.post('/api/photos',formData).subscribe(
(data: any) => {
response = data;
},
err => {
console.log(err)
}
);
}
As description variable is a string, I get the following error on my console:
ERROR TypeError: "Argument 2 of FormData.append is not an object."
NOTE:
Even if that can seem out of subject I added tags for the backend server on my post as I'm open to solve this issue creating a file on the backend also.
description is not a file because probably it's not present on the client side.
formData.append() is used to append the files with formData to upload them with form data.
Well you can not save a file to server using javascript.
see it has already been answerd here
(Saving a text file on server using JavaScript)

How can I save a drag and dropped image to the server?

First of all, background.
Everything is behind a corporate firewall, so there is no showing a live version or accessing nifty tools like nodeJS or many libraries.
I have HTML, php 5, javascript, and jquery1.9.
I have an web window with a bunch of data. I want to allow users to be able to drop a picture called a sleuth image into a box, show that box, and save that image in a special location on my server. The sleuth image is a dynamically generated graph on a different internal server that I have no privileges whatsoever on (another department). While it could be named anything, I want to save it with a specific name so it displays properly later when the web window for this data is reloaded.
I have this javascript function which allows them to drop an image and displays it. I just need it to save the image to a .png.
function drop_handler(event) {
// this is part of the ability to drag sleuth images onto the OOC
// Prevent default behavior (Prevent file from being opened)
event.preventDefault();
var items = event.dataTransfer.items;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.kind === 'string') {
item.getAsString(function(data) {
document.getElementById("sleuth").innerHTML = data;
});
}
}
}
I need to save the img src that show up in the variable "data" AS "sleuthImg.png"
Yes, I know I need to add validation. First, I need this part to work.
First, you will need an endpoint on the server that can accept files and store them. Assuming you have that part already, then:
Get the file from the dataTransfer object
https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/files
Then create a new FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData
var formData = new FormData();
formData.append('file', fileFromDataTransfer);
formData.append('mime_type', fileFromDataTransfer.type);
(where 'file' is the name of the post parameter that your server is expecting. 'mime_type' is another form data parameter included as an example)
Then, using the request-making library of your choosing, make a POST request with the form data.
post('your/upload/endpoint', formData);

return only the image from an object file

I'm pulling a base64 encoded image from a server to a website and want to automatically use the image. The image comes within an object file and I'm not sure how to extract just the image from the object.
Server send the object using (Node.js server):
res.send(result[0]);
The website get request and display code:
getImage() {
this.httpClient.get('http://ip_address/route/imagename')
.subscribe(data => {
this.getImg = data;
console.log(data);
});
The result is an object containing the image, but I want the image to display on its own, outside of the object. I don't know if that needs happens on the server, or on the website, but i dont know either way..
console log image on website link
I needed to save the data file to a variable then save it to a different variable, specifying the part I wanted in the first variable. Like:
this.httpClient.get('ip_address/images/' + imgName)
.subscribe(data => {
this.imageData = data;
this.base64image = (this.imageData.image);
this.base64image can then be used as the base64 code.

Using Google Cloud Datastore and AJAX(blobs)-python

Hi I have some images stored as BlobProperty in Google Cloud Datastore. I am trying to load these images via ajax into my template. For eg:- a user has an image and a name. Now the image and name area gets populated via an AJAX get call to the server. I am not understanding how to I send these images to the client , JSON wont support binary data. However googling around tells me of something called base 64.(I am quite new to all this, so let me admit , I am a noob).
Is this the only way to handle this or is there some other better way.
This thread suggests that if you just create an image element, set its src, and add it to your page using Javascript, the browser will take care of making an HTTP request for the image:
http://bytes.com/topic/javascript/answers/472046-using-ajax-xmlhttprequest-load-images
If you do want to do it with 'pure' AJAX, then base64 is probably the best thing: it's a way of encoding binary data (like images) as text, so you can send it as a long string in json.
This is how I do it, it's in flask but nonetheless it's python
this way, you create a request handler to display the images.
So all you need to do to get the image via ajax is getting the image id to be served. It's simpler and you can manipulate the size as well on the fly
from flask import request
from google.appengine.api import taskqueue, images, mail
from google.appengine.ext import db
#app.route('/image/<img_id>')
def imgshow(img_id):
imageuse = Image.all().filter("image_id =", img_id).get()
if imageuse:
response = Response(response=imageuse.content)
#you can use any type over here
response.headers['Content-Type']='image/png'
return response
else:
return
this is what I do to manipulate the size
#app.route('/thumb/<img_id>')
def thumbshow(img_id):
imageuse = Image.all().filter("image_id =", img_id).get()
if imageuse:
thbimg = images.resize(imageuse.content, 80)
response = Response(thbimg)
response.headers['Content-Type']='image/png'
return response
else:
return
hope that helps

Categories

Resources