Getting BLOB data from XHR request in ionic 2 - ionic-framework

Can any one tel that how to GET Blob XHR request and XMLHttpRequest in ionic 2 , i have to fetch image url from the api .
This is my Ajax Code, i want in ionic 2
xhr.open('GET', "https://getbytitle('LE_COE_Mapping')/items(2)/AttachmentFiles('3.jpg')/$value");
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// xhr.setRequestHeader('Authorization', 'Token token="' + token + '"');
xhr.setRequestHeader('Authorization', token);
xhr.onload = function (e) {
var img = new Image();
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
document.getElementById('Doctitle').appendChild(img);
// alert(url.createObjectURL(this.response));
};
xhr.send();
Please i am stuck in this from the last two days.
Please Help me.
Thanks

I also got stuck in same problem once then this what I did :
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is your final response
console.log(this.response, typeof this.response);
var img = // your img syntax
//your any custom code goes here
}else{
//show error message if you want to show
}
}
xhr.open('GET', 'http://Your image url');// image url be like http://ab.cd/img.png
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send authorisation if you sending token
xhr.send();
Hope this will help you.

what i solved this below:
this.array: this is the url which we pass to get the blob url of the particular url:
const headers1 = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "Bearer " + this.accessToken,
'X-Requested-With': 'XMLHttpRequest'
})
const response = await this.http.get(this.array + "/$value", { headers: headers1, responseType: 'blob' }).toPromise();
let b: any = new Blob([response], { type: 'application/octet-stream' });
var url = window.URL.createObjectURL(b);
console.log("this is url BLOB " + url);

Related

Text to speech. Output audio was not playing or supporting after encoding in my system

const fs = require('fs');
//var base64 = require('base64-stream');
//const getStream = require('get-stream');
var text = "Microsoft Speech Service Text-to-Speech API"
function texttospeech(text) {
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://southeastasia.tts.speech.microsoft.com/cognitiveservices/v1',
'headers': {
'Authorization': 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJyZWdpb24iOiJzb3V0aGVhc3Rhc2lhIiwic3Vic2NyaXB0aW9uLWlkIjoiZDI3YWM4ZWZlZDEyNDQ4ZTk1YmFhNWQ2MTMxODliZmUiLCJwcm9kdWN0LWlkIjoiU3BlZWNoU2VydmljZXMuRjAiLCJjb2duaXRpdmUtc2VydmljZXMtZW5kcG9pbnQiOiJodHRwczovL2FwaS5jb2duaXRpdmUubWljcm9zb2Z0LmNvbS9pbnRlcm5hbC92MS4wLyIsImF6dXJlLXJlc291cmNlLWlkIjoiL3N1YnNjcmlwdGlvbnMvMjgzZjZiOGMtMzQzOC00Yjk1LTkwOTYtOWMwZjMwNTFhMDYzL3Jlc291cmNlR3JvdXBzL3ByYWNiaXotcG9jLXJnL3Byb3ZpZGVycy9NaWNyb3NvZnQuQ29nbml0aXZlU2VydmljZXMvYWNjb3VudHMvdGV4dHNwZWVjaGV4Iiwic2NvcGUiOiJzcGVlY2hzZXJ2aWNlcyIsImF1ZCI6InVybjptcy5zcGVlY2hzZXJ2aWNlcy5zb3V0aGVhc3Rhc2lhIiwiZXhwIjoxNjUzMzYyODQ1LCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMifQ.I79ZqJX3GP7gwtdx8FXFENOswQIHAAbVwPP07SEKS6g',
'Content-type': 'application/ssml+xml',
'X-Microsoft-OutputFormat': 'audio-16khz-32kbitrate-mono-mp3',
'User-Agent': 'texttospeech',
'Cookie': 'ARRAffinity=0f0eac9025c535aa027b3d037b337eec6b27b4947463810f5ef9458235c67a5d; ARRAffinitySameSite=0f0eac9025c535aa027b3d037b337eec6b27b4947463810f5ef9458235c67a5d'
},
body: '<speak version=\'1.0\' xml:lang=\'en-US\' xmlns:mstts="https://www.w3.org/2001/mstts">\r\n<voice xml:lang=\'en-US\' xml:gender=\'Male\' name=\'en-US-JennyNeural\'>\r\n<mstts:express-as role="YoungAdultFemale" style="calm" styledegree="2">\r\n<mstts:silence type="Sentenceboundary" value="200ms"/>\r\n Hi, Welcome to iNextLabs <break time="1000ms" /> \r\n <lang xml:lang="fr-FR">\r\n How can i help you?\r\n </lang>\r\n </mstts:express-as>\r\n</voice></speak>'
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
//var encoder = new base64.Base64Encode();
//var b64s = request(options).pipe(encoder);
//var strBase64 = yield getStream(b64s);
const fs = require('fs');
const wavUrl = 'data:audio/wav;base64,' + response.body;
const buffer = Buffer.from(wavUrl.split('base64,')[1], // only use encoded data after "base64,"
'base64');
fs.writeFileSync('./response13.mp3', buffer);
});
}
texttospeech()
I have usedtext to speech. Followed this document to get the text to speech. while running through postman the response clip was playing. But when im putting it in my code and encoding it the voice is not supporting.

How to insert file to a shared drive using REST on Apps Script?

Is there a way that we can upload files to shared drive using POST Method? I don't know how to call the Drive ID of the shared drive and target it to the URL fetch function, is this possible?
This is my code:
var DriveScope = 'https://www.googleapis.com/auth/drive';
var ServiceAccountPrivateKey ="-----BEGIN PRIVATE KEY----"
var ServiceAccountEmail = "drive-uploads#xxxxxxx.com";
function testinRest(){
var service = getDriveService();
var driveID = "XXXXXXXX";
var APIKey = "XXXXXXXXXXXXX";
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
'name': 'Bob Smith',
'email': 'bob#example.com',
'resume': resumeBlob
};
var url = 'https://www.googleapis.com/drive/v3/drives';
var output = UrlFetchApp.fetch(url, {
method: 'get',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json'
}).getContentText();
var response= JSON.parse(output);
for(var i=0; i < response.drives.length; i++){
if(driveID == response.drives[i].id){
service.reset()
if (service.hasAccess()) {
var newPresentationName = "RJ POGI";
var url = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true&key=' + APIKey;
var body = {
"name": newPresentationName,
"parents": [driveID]
};
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
Referer:'https://explorer.apis.google.com'
},
method: 'post',
payload: formData,//JSON.stringify(body),
contentType: 'application/json',
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params).getContentText();
Logger.log('response: ' + response);
var id = JSON.parse(response).id;
return id;
}
}
}
}
function getDriveService(){
var service = OAuth2.createService('drive').setTokenUrl('https://accounts.google.com/o/oauth2/token').setPrivateKey(ServiceAccountPrivateKey).setClientId(ServiceAccountEmail).setPropertyStore(PropertiesService.getUserProperties()).setScope(DriveScope);
//console.log("Service::" + service);
//console.log('Service Has Access::' + service.hasAccess());
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}else{
return service;
}
}
function reset() {
var service = getDriveService();
service.reset();
}
On this example, I want the resumeBlob to be inserted on the targeted DriveID. Any help will be appreciated. Thanks!
Your problem needs to be divided in three steps:
Create a file on the drive with UrlFetchApp
Pass a content to the file
Insert the file into a shared drive
Now, you original question - 3. is easy to solve, you just need to specify in your requestsupportsTeamDrives=true.
More difficult is the combination of 1. and 2..
The Files: create method offers either an URI for media upload only requests, or for metadata-only.
The workaround would be to perform a resumable Upload, which allows you to post the metadata first, and add the file contents later.
The URI you need to use would be "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable".
Sample:
function uploadToSharedDrive(){
var url = "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable";
var resumeBlob = Utilities.newBlob('Hire me!');
var formData = {
'name': 'Bob Smith',
'mimeType': 'text/plain',
'parents': [
"ID of the shared drive"
]
};
params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
contentType: 'application/json',
method: 'post',
payload: JSON.stringify(formData),
}
var response = UrlFetchApp.fetch(url, params);
Logger.log(response.getContentText());
data = resumeBlob.getBytes();
var params2 = {
method: "put",
payload: data,
muteHttpExceptions: true,
};
var location = response.getHeaders().Location;
var response = UrlFetchApp.fetch(location, params2);
Logger.log(response.getContentText())
}

Angular 2 http post is returning 200 but no response is returned

My http call is returning 200 but no response is captured. My code inside subscribe is not being hit. The API is returning data when I test in postman. Here is my code.
getToken(authcode: string) {
var data = 'client_id=InspectWebApp_client&code=' + authcode + '&redirect_uri=http://localhost:3000&grant_type=authorization_code';
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
this.http.post('https://fedloginqa.test.com/as/token.oauth2', data, options)
.subscribe((res: Response) => {
var resultsToken = res.json();
localStorage.setItem("access_token",resultsToken.access_token)
//return this.inspections;
})
}
I was also facing the same problem. The problem was solved using the map function on Observables. Here is my implementation:
login(Username:string, Password:string) : Observable<Response>{
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa(Username + ":" + Password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this._http.post(this._baseUrl+"auth/login", " " , {headers: headers} )
.map((response: Response) => {
return response;
}).catch(this.handleError);
}
Here the handleError is a function to catch the excceptions generated. This is a function in login.service.ts that sends the username and password to the api to get data. You can see that I am returning response from the map function in this service. Now, this returned response can be caught in subscribe function in following way:
this._loginService.login(this.username, this.password)
.subscribe(
(response) => {
//Here you can map the response to a type.
this.apiResult = <IUser>response.json();
},
(err) => {
//Here you can catch the error
},
() => {this.router.navigate(['home'])}
);

ionic 2 http request after oauth not working

I have a button redirect to this function
loginGoogle() {
this.cordovaOauthG.login().then((success) => {
console.log("Google Login DONE ");
if (success != null) {
console.log(JSON.stringify(success));
//alert(success.access_token);
if (success.access_token != null && success.access_token != '') {
var params = "google_id=" + success.access_token;
// var token = success.access_token;
// this.postLoginGoogle(params);
this.tesLogin();
}
}
}, (error) => {
alert(error);
});
}
and this is the function for http request
tesLogin(){
// var params = "google_id="+gid;
var params = "google_id="+'ya29.Ci_4ApeVHCD7av30Y82JRZPLG4T9ZUgmU1SNLUGIlVV_ufAcCoBc4ILqsY6Ah55i-g';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
console.log(params);
this.http.post(Config.base_url + 'api/user-account/login-google', params, {headers: headers})
.map(res => res.json()).subscribe(data => {
console.log(data);
if (data.success) {
this.local.set('access_token', data.message);
this.menu.enable(true);
this.nav.setRoot(HomePage);
}
else {
this.doAlert("Incorrect email or password");
}
});
}
My problem is, whenever I tried to call using success.access_token, it doesnt work
but If I am calling the request without any parameters(just throwing in some random strings) then it works
I tried to debug it using mobile inspector from chrome, either way it is returning a error like this (working post & not working post both returning error)
EXCEPTION: SyntaxError: Unexpected token < in JSON at position 1
I suggest to send the authentication token in the header not in the parameters. Something like that:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Bearer ' + authToken);

How to send facebook api batch request with node.js

How do I send facebook api batch request with node.js?
FB's examples do not work.
but I finally got danwong/restler.js to work like this:
exports.updateUserFriends = function (userData, next) {
var TOKEN = userData[1];
var fbID = userData[3].id;
var batchreq = {};
batchreq.batch = [];
batchreq.batch.push({"method":"GET", "relative_url":fbID+"/"});
batchreq.batch.push({"method": "GET", "relative_url":fbID+"/friends?limit=50"});
restler.post('https://graph.facebook.com?access_token='+TOKEN,
{data:"batch="+JSON.stringify(batchreq.batch)})
.on('complete', function(data) {
console.log(data);
return next;
});
};
So I thought I'd post this to save someone else a bit of frustration.
First thing to note is that, "Only POST is allowed for batch requests" in FB Api.
var https = require('https');
var url = '/?access_token='+ YOUR_ACCESS_TOKEN_HERE,
batch=[{
"method":"GET",
"relative_url":page + "/insights"
}, {
"method": "GET",
"relative_url":page
}];
url = url + '&batch=' + JSON.stringify(batch);
console.log(url);
var options = {
host:'graph.facebook.com',
path:url,
method: 'POST'
};
var req =https.request(options, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body='';
res.on('data', function(chunk){
// console.log("body:" + chunk);
body += chunk;
});
res.on('end', function(){
var fbRes = JSON.parse(body);
console.log(fbRes);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();