Get image byte/base64 from URL - javascript

I'm looking for a solution where I can provide URL to specific image and then with Javascript I retrieve data of that image. I alread found that I can't just pull file through, so maybe byte array or base64 will do?
To be specific before someone downvote that question: I want to parse URL and get image to my server in any form. There is a lot similar questions, but none of them answers this one.
What I need that for? I have access to API where I also am provided with image url's, but I want them to be uploaded to my server via Background Job in Parse.com service (something like CRON job). I know how to link file with ParseObject, but can't find solution how to download image directly to ParseCloud and link it.
var Image = require("parse-image");
Parse.Cloud.job("getImagesJob", function(request, status) {
Parse.Cloud.useMasterKey();
var beerObj = Parse.Object.extend("My_class");
var query = new Parse.Query(beerObj);
query.first().then(function(objs) {
var brew = objs.get("brewery");
var bname = objs.get("beer_name");
//var fullName = brew + " " + bname;
var fullName = "Browar Name";
console.log(fullName);
return Parse.Cloud.httpRequest({
method: 'GET',
url: 'api server address',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
q : fullName,
client_id : '...',
client_secret : '...'
}
}).then(function(httpResponse) {
var json = JSON.parse(httpResponse.text);
if(json.meta.code === 200){
if(json.response.beers.count > 0){
if(json.response.beers.items[0].beer.beer_label === "/default.png"){
console.log("brak etykiety dla " + fullName);
} else {
console.log("znaleziono etykietę dla " + fullName);
Parse.Cloud.httpRequest({ //NOT REACHING
url: json.response.beers.items[0].beer.beer_label,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
objs.set("logo", image.data());
console.log("udalo sie dolaczyc");
},
error: function(error) {
// The image data was invalid.
console.error(error);
}
})
},
error: function(error) {
// The networking request failed.
}
});
}
} else {
// daj cokolwiek żeby się nie zacięło na jednym
console.log("Brak danych dla piwa: " + fullName);
}
}
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status + httpResponse.text);
});
}).then(function(obj) {
status.success("Zrobione");
}, function(error) {
status.error(error);
});
});

You can use parse-image module in Cloud Code as in their documentation
var Image = require("parse-image");
Parse.Cloud.httpRequest({
url: YOUR_URL,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
console.log("Image is " + image.width() + "x" + image.height() + ".");
},
error: function(error) {
// The image data was invalid.
}
})
},
error: function(error) {
// The networking request failed.
}
});
With above code, you can get image data in Buffer using image.data(). To get base64 data, use image.data().toString("base64")

Related

I cannot send a part of data from chrome extension to Spreadsheet via GAS

I want to send some data from chrome extension to Spreadsheet via GAS, but only "last" is dropped, although "Title" and "URL" is sent successfully.
Hence, could you kindly check the code?
const gasUrl = "here is my spreadsheet GAS url";
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
title = tabs[0].title;
url = tabs[0].url;
last = url.slice(-8); // I want to send url's last 8 letters.
console.log(`Title: ${title}`);
console.log(`URL: ${url}`);
console.log(`Last: ${last}`); // I can see "last" is worked as intend here.
});
$(function() {
$('#doit').on('click', function() {
post2GAS(title, url, last);
});
});
function post2GAS(title, url, last){
const data = {
title: title,
url: url,
last: last
}
$.ajax({
type: 'POST',
url: gasUrl,
data: JSON.stringify(data)
})
.done(function (data) {
console.log("success"); // I can see success on console.
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("failed");
console.log("XMLHttpRequest : " + jqXHR.status);
console.log("textStatus : " + textStatus);
console.log("errorThrown : " + errorThrown);
})
.always((data) => {
console.log("finished"); // I can see finished on console.
});
}
Seems GAS cannot catch "last" param correctly, but I cannot find specific reason.
Here is GAS code.
function doPost(e) {
var params = JSON.parse(e.postData.getDataAsString());
var title = params.title;
var url = params.url;
var last = params.last;
var sheet = SpreadsheetApp.openById('Sheet ID').getSheetByName("Sheet Name");
sheet.appendRow([title, url, last]);
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.JSON);
output.setContent(JSON.stringify( { sucsess: true }));
return output;
}
Thanks,
I'm so sorry, I have not deploy new GAS.
And when I deployed, it's solved.
Hence, I'm close this ticket here.

chrome.storage.local.get not working

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

Response string JavaScript undefined

I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);

Unable to get access and refresh token after authenticating with Google API

I followed this awesome tutorial to get the access and refresh tokens once the user logged in with their google account, but I always this response when I call GetAccessCode():
{
"error": "invalid_request"
}
Here's my code:
var url = window.location.href;
if (url.indexOf("code=") > 0) { //Once the user signed in with Google
var code_starts = url.indexOf("code=");
var code = url.substring((code_starts + 5), url.length);
alert("Code= " + code);
GetAccessTokens(code);
} else if (url.indexOf("access_token=") > 0) { //Get the tokens, but I never get this far
var at_starts = url.indexOf("access_token=");
var exp_starts = url.indexOf("expires_in=");
var access_token = url.substring((at_starts + 13), exp_starts);
alert("AT= " + access_token);
var rt_starts = url.indexOf("refresh_token=");
var id_starts = url.indexOf("id_token=");
var refresh_token = url.substring((rt_starts + 14), id_starts);
alert("RT= " + refresh_token);
} else {
GetAccessCode(); //If user opens the page, show him the consent screen
}
function GetAccessCode() {
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://mywebsite.com/quickstart.html' + '&response_type=code' + '&client_id=' + clientId + '&scope=' + scopes + '&approval_prompt=force' + '&access_type=offline';
}
function GetAccessTokens(code) {
window.location = 'https://accounts.google.com/o/oauth2/token?code=' + code + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=https://mywebsite.com/quickstart.html' + '&grant_type=authorization_code';
}
Here I receive the invalid_request error.
I tried to get the tokens via an ajax request to not have to redirect the page again (bad UX):
var red = 'https://mywebsite.com/quickstart.html';
var options = {
url: 'https://accounts.google.com/o/oauth2/token',
type: "POST",
dataType: "json",
data: "code=code&client_id=clientId&client_secret=clientSecret&redirect_uri=red&grant_type=authorization_code",
complete: function (e) {
alert(e);
alert(e.status);
},
};
$.ajax(options);
}
I tried it with headers, too:
headers: { "Content-type": "application/x-www-form-urlencoded"},
And I tried it this way, too:
$.ajax({
url: "https://accounts.google.com/o/oauth2/token",
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
alert(response); //I never get this
var json = $.parseJSON(response);
}
})
.fail(function(err) {
alert("error" + err); //I get [Object object]
});
And a few other stuff, too.
Oh, and all the parameters have the correct value.
Any ideas?
Ps: The oauth playground shows that the corrent token url is https://www.googleapis.com/oauth2/v4/token but when I use it I get Not found in the browser.
After 3 days I did it. Thanks for the console.log tip, #Brunt!
$.ajax({
url: 'https://www.googleapis.com/oauth2/v4/token',
type: "post",
datatype:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async : true,
data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
success: function(response){
console.log("Response: " + response);
console.log("AT: " + response['access_token']);
console.log("RT: " + response['refresh_token']);
access_token = response['access_token'];
refresh_token = response['refresh_token'];
}
})
.fail(function(err) {
alert("error" + err); //[Object object]
console.log("error" + err);
});

How do I get the src_small url from an FQL Query with the object_id returned after uploading an image my facebook profile via javascript?

Hello I have tried several resources now but can't seem figure out how to return the src_small url after posting an image to facebook via javascript. I'm getting the object_id as a response and then I'm trying to perform and FQL query to get the small and large url....the upload function executes fine, then the fql query doesn't return anything. Any help would be much appreciated.
function uploadphoto() {
var imgURL = "img_URL";
FB.api('me/photos', 'post', {
url: imgURL, message: 'Pura Vita'
}, function (response) {
if (!response || response.error) {
alert(response.error);
} else {
alert(response.id);
getPhotoInfo(response.id);
}
});
}
function getPhotoInfo(oid) {
FB.api(
{
method: 'fql.query',
query: 'Select src_big,src_small from photo where aid in(SELECT aid FROM album WHERE owner = me()) and object_id =' + '"' + oid + '"'
},
function (response) {
alert('Post url: ' + JSON.stringify(response));
});
}
One more hour and I realized I didn't have the correct permissions set!

Categories