How to send a base64 image in postman - postman

Need to make a request to a api with a image encoded in base64, the request is a put, and i was trying making in the body section using the raw format and adding i.e. this json:
{
"picture": {
"name": "/Users/Cokeina/Desktop/imagenes/default_avatar.png",
"content_type": "image/png",
"file": "base64string"
}
}
but seems like this isn't working, what is the correct way to do this?

You could find online base64 image encoder. They encode an image to a string.
The example of raw body in JSON format in the POSTMAN:
"profile": {
"first_name": "John",
"last_name": "Dow",
"photo": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="
}
I think, that "name" and "content_type" is obvious in your JSON.

This is how I do it:
// JSON body in Postman
{
"first_name": "John",
"last_name": "Doe",
"photo": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABJgAAASsCAYAAADDvzILAAAZy3pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZpZkhw5kkT/cYo5AvblOIZNpG8wx5+niCSHZBWlq7v6Z0SGyczIjMUdDlPTBXB3/vsf1/0X/2rx2eXSeh21ev7lkUc0fun+88/ez+Dz+/n+jf7+0t8/Pe9sfb0QeSrxmD4v9Pp5DN+e//rAt8dg/FZ+OFBfXy/Mn18Yn8P72H85..."
}
Then on the server, I store the image like so:
app.use(express.json({ limit: '50mb' })); // To allow for larger payloads
app.post("/selfie", (req, res) => {
console.log('req.body:', req.body);
var base64Data = req.body.photo.replace(/^data:image\/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function (err) {
console.log(err);
});
res.end();
});

This is working for me:
let template = `
<img src='data:image/jpeg;base64,{{img}}'/>
`;
pm.visualizer.set(template, {
img: pm.response.json()
});
while the response is the base64 string

Related

Bypass custom payload from Whatsapp API or custom integration to dialogflow ES API

I use a Dialogflow API as NLP and the interface that we use is Whatsapp API.
my problem is, when I want to bypass Text and Whatsapp client number to Dialogflow (my reference), I didn't found document to explain that. for comparison, the Telegram official integration dialogflow, from the body request we can extract that data like name and Telegram user ID.
const sessionId = phone_number_id; //session ID get from phone number
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
const request = {
session: sessionPath,
queryInput: {
text: {
text: msg_body,
languageCode: "id-ID"
},
},
payload: {
data: "testing",
phoneNumber : phone_number_id
}
};
console.log("request", request);
await sessionClient.detectIntent(request).then(responses => {
console.log("DetectIntent", JSON.stringify(responses));
}).catch(err => {
console.error("ERROR:", err);
})
I tried it with request variable like that but in request body in dialogflow fulfillment, it never showed up
{
"responseId": "censored",
"queryResult": {
"queryText": "halo",
"action": "input.welcome",
"parameters": {},
"allRequiredParamsPresent": true,
"fulfillmentText": "error",
"fulfillmentMessages": [
{
"text": {
"text": [
"error"
]
}
}
],
"outputContexts": [
{
"name": "censored",
"parameters": {
"no-input": 0,
"no-match": 0
}
}
],
"intent": {
"name": "censored",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1,
"languageCode": "id"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "censored"
}
#Maulana ahmad, As you have mentioned in the comment below example code can be referred to extract data from the body request.
const dialogflow = require('dialogflow');
// Import the JSON to gRPC struct converter
const structjson = require('./structjson.js');
// Instantiates a sessison client
const sessionClient = new dialogflow.SessionsClient();
// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
event: {
name: eventName,
parameters: structjson.jsonToStructProto({foo: 'bar'}),
languageCode: languageCode,
},
},
};
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
logQueryResult(sessionClient, responses[0].queryResult);
})
.catch(err => {
console.error('ERROR:', err);
});
This Stack Overflow link can be referred for more information.
Posting the answer as community wiki for the benefit of the community that might encounter this use case in the future.
Feel free to edit this answer for additional information.

Send an image to server through fetch using expo-image-picker React Native

I want to upload and image from my gallery using expo-image-picker and send it to the server through fetch.
expo-image-picker to Upload image Code:
const [photo, setPhoto] = React.useState(null)
const chooseImage = async ()=> {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect:[4,3],
quality:1
})
console.log(result)
if(!result.cancelled){
setPhoto(result.uri)
}
}
Fetch Code:
export const createRestaurantFetch = (endpoint, inputName, inputType, inputDescription, inputAddress, img, touken)=> {
let bearer = 'Bearer ' + touken;
var files = new FormData();
files.append('name',inputName)
files.append('type',inputType)
files.append('description',inputDescription)
files.append('address',inputAddress)
files.append('photo',img)
console.log(files)
fetch(endpoint, {
method: "POST",
body: files,
headers:{
'Authorization': bearer
}
}).then(res =>{
/* console.log("POST RESPONSE: "+JSON.stringify(res)); */
/* console.log(res.status); */
if(res.status==200) {
res.json().then((data) => {alert(data.message)});
}else res.json().then((data) => {alert(data.msg)});
})
.catch(error => console.error('Error:', error))
/* .then(response => console.log(response)); */
}
console.log(files) shows:
FormData {
"_parts": Array [
Array [
"name",
"Resto",
],
Array [
"type",
"Fastfood",
],
Array [
"description",
"Atnight",
],
Array [
"address",
"Springfield",
],
Array [
"photo",
"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540daolavez%252Fubereats/ImagePicker/dfaedaaf-3c1f-49ea-88ce-e62c9e674115.jpg",
],
],
}
Function that receives body of fetch on server side:
export const createRestaurant = async (req: any, res: Response) => {
const body=req.body;
const files = req.files;
try {
if (!files || Object.keys(files).length === 0 || !files.photo ) {
res.status(400).json({
done: false,
msg: 'There is no photo uploaded, please try again.'
});
}
} catch (e) {
console.error(e);
};
So first I fill the inputs(that is the data you see in the first line of Fetch Code), then I upload the image as you can see, then I hit "Create" button and it executes the Fetch Code, and then you can see in the content of the formData in the console.log(files) just so you know it's wrapping the data well to send it, and in the end the response from the server is the msg you see in the code which is 'There is no photo uploaded, please try again.' meaning that it doesn't recognize the file that I send. I'm not sure how I can achieve this, any suggestions?
By the way, that img parameter in the first line of the Fetch Code is the image that I'm passing from a function to the Fetch

Postman - How to replace values for all specific properties in the JSON Response, to use it later as another Request's Body

I have 2 API requests. 1st one is GET, that returns a response. This response is used as a Body/Payload in the 2nd request (POST). BUT the Payload should have certain values to be replaced before used in the 2nd request (in my case below it should be value for "Status" property).
How can I do it?
Here is my example Response:
{
"Variations":[
{
"ItemIds":[
"xxx"
],
"Items":[
{
"Id":"67-V1",
"GuId":"xxx",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 1",
"Id":"67-V1"
},
{
"ItemIds":[
"yyy"
],
"Items":[
{
"Id":"67-V2",
"GuId":"yyy",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 2",
"Id":"67-V2"
},
{
"ItemIds":[
"zzz"
],
"Items":[
{
"Id":"67-V3",
"GuId":"zzz",
"Type":"Unit",
"Status":"Active"
}
],
"Name":"VAR 3",
"Id":"67-V3"
}
],
"ItemIds":[
],
"Items":[
],
"Name":"MAINP",
"Id":"67",
"Color":null
}
Here is my code, but it does not seem to work (the replacement part):
var jsonData = pm.response.json();
function replaceStatus() {
_.each(jsonData.Variations, (arrayItem) => {
if(arrayItem.Items.Status !== "NonActive") {
arrayItem.Items.Status == "NonActive";
console.log("arrayItem " + arrayItem);
}
});
}
pm.test("Run Function", replaceStatus ());
pm.sendRequest({
url: 'localhost:3000/post',
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res)
})
I guess you are trying to replace all NonActive values with Active. In that case, you should use = for assignment not ==. The JSON file you provided is not valid and couldn't run your code on my machine. I am happy to have a closer look if that didn't work
Based on your updates these changes need to be made
1- in order to deal with JSON object you need to parse the response as it is string and you can't call sth like JsonData.Variations on that.make sure jsonData is a JSON object. if not add sth like this to parse it
var parsedJson = JSON.parse(jsonData)
2- It seems that you missed one array layer in your function to iterate over items. As you have two nested arrays to reach Status the replaceStatus function should be as below
function replaceStatus() {
_.each(parsedJson.Variations, (arrayItem) => {
_.each(arrayItem.Items, (item) => {
if(item.Status !== "NonActive") {
item.Status = "NonActive";
console.log("arrayItem " + item.Status);
}
});
});
}
Have you posted your entire code in the tests section or only a part of it?
I saw from one of your comments that you cannot see the output logged to the console.
This may be very trivial, but, if you did post your entire code, it looks like you may have forgotten to call your replaceStatus() function before your post call.

Get speech mark from Amazon Polly using NodeJs

I am working on an animation project to add subtitle to what my character says. I can get the mp3 file from AWS Polly with no issue.
However, when I want to get each part of the word separately, it doesn't work. I checked inspector tab, and I can see some params are passing to request to polly.aws. Any idea how I get json/mark-up file to know the start and end of each word & sentence?
const AWS = require('aws-sdk')
const Fs = require('fs')
const Polly = new AWS.Polly({
signatureVersion: 'v4',
region: 'us-east-1'
})
// # this part works fine
let params = {
'Text': 'Hi, my name is Soley. We are building something amazing!',
'OutputFormat': 'mp3',
'VoiceId': 'Matthew'
}
// # from chrome's network tab:
// # and is there a way to get mp3 and mark-up text at the same time?
// "text": "Hi, my name is Soley. We are building something amazing!",
// "textContentType": "text",
// "voiceId": "Matthew",
// "languageCode": "en-US",
// "engine": "standard",
// "outputFormat": "json-8000",
// "lexiconNames": [],
// "speechMarksTypes": [
// "word",
// "sentence"
// ]
Polly.synthesizeSpeech(params, (err, data) => {
if (err) {
console.log(err)
} else if (data) {
console.log(data)
if (data.AudioStream instanceof Buffer) {
Fs.writeFile("speech."+params.OutputFormat, data.AudioStream, function (err) {
if (err) {
return console.log(err)
}
console.log("The file was saved!")
})
}
}
})
some useful links to check: https://aws.amazon.com/blogs/aws/new-amazon-polly-speech-marks/
using cli also works file: https://docs.aws.amazon.com/polly/latest/dg/speechmarkexamples.html but I want it in NodeJs
Oh, I think I found something:
let params = {
'Text': 'Hi, my name is Soley. We are building something amazing!',
'OutputFormat': 'json',
'VoiceId': 'Matthew',
'SpeechMarkTypes': ['word', 'sentence']
}
Thanks to java: https://docs.aws.amazon.com/polly/latest/dg/SynthesizeSpeechMarksSample.html

How can I see my response from server in Ember.js

My code is quite simple (Client Side):
Record.Router.map(function () {
this.resource('main', { path: '/' });
});
Record.MainRoute = Ember.Route.extend({
model: function () {
var response = Record.Rank.find();
console.log(response.get('name'));
console.log(response);
return Record.Rank.find();
}
});
My model:
Record.Rank = DS.Model.extend({
id: DS.attr('integer'),
rank: DS.attr('integer'),
content: DS.attr('string')
});
I use RESTadapter:
Record.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.reopen({
namespace: 'recordApp'
})
});
My Server side code (PHP):
<?php
namespace RecordContainer;
echo '{"rank":
{
"id": "1",
"rank": "2",
"content": "walla"
}
}';
I expect to something after I issue Record.Rank.find() but my console.log(response.get('name')) logs undefined and the second console.log(response) show the following, no information about echo from server inside:
How do I see the response from the server, in Ember?
1st: Calling find on a DS.Model without any parameters, i.e. Record.Rank.find(), is equivalent to sending a findAll() request to your server. In other words, it should fetch all Record.Rank. Therefore ember-data expects an array in the response of the format:
{
"ranks":[
{
"id": "1",
"rank": "2",
"content": "walla"
},
{
"id": "2",
"rank": "5",
"content": "foo"
}
]
}
2nd: Even if the response from the PHP was correct (as described above), console.log(response.get('name')); would probably return undefined since the request is not yet completed and the record(s) are not available. If you really want to access the records loaded into the store you need to place your code into a Promise resolve callback:
Record.MainRoute = Ember.Route.extend({
model: function () {
var response = Record.Rank.find();
response.then(function(ranks) {
console.log(ranks.getEach('name'));
});
return response;
}
});