Adding array of images to Firebase using AngularFire - image

I'm trying to allow users to upload images and then store the images, base64 encoded, in firebase. I'm trying to make my firebase structured as follows:
|--Feed
|----Feed Item
|------username
|------epic
|---------name,etc.
|------images
|---------image1, image 2, etc.
However, I can't get the remote data in firebase to mirror the local data in the client. When I print the array of images to the console in the client, it shows that the uploaded images have been added to the array of images...but these images never make it to firebase. I've tried doing this multiple ways to no avail. I tried using implicit syncing, explicit syncing, and a mixture of both. I can;t for the life of me figure out why this isn;t working and I'm getting pretty frustrated. Here's my code:
$scope.complete = function(epicName){
for (var i = 0; i < $scope.activeEpics.length; i++){
if($scope.activeEpics[i].id === epicName){
var epicToAdd = $scope.activeEpics[i];
}
}
var epicToAddToFeed = {epic: epicToAdd, username: $scope.currUser.username, userImage: $scope.currUser.image, props:0, images:['empty']};
//connect to feed data
var feedUrl = "https://myfirebaseurl.com/feed";
$scope.feed = angularFireCollection(new Firebase(feedUrl));
//add epic
var added = $scope.feed.add(epicToAddToFeed).name();
//connect to added epic in firebase
var addedUrl = "https://myfirebaseurl.com/feed/" + added;
var addedRef = new Firebase(addedUrl);
angularFire(addedRef, $scope, 'added').then(function(){
// for each image uploaded, add image to the added epic's array of images
for (var i = 0, f; f = $scope.files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
$scope.added.images.push(filePayload);
};
})(f);
reader.readAsDataURL(f);
}
});
}
EDIT: Figured it out, had to connect to "https://myfirebaseurl.com/feed/" + added + "/images"

Related

receive file in my xamarin app from another's app share function

How to receive file in my xamarin app from another's app share function?
if (Intent.Action == Intent.ActionSend)
{
{
// This is just an example of the data stored in the extras
var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) asAndroid.Net.Uri;
var subject = Intent.GetStringExtra(Intent.ExtraSubject);
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
var pdfStream = ContentResolver.OpenInputStream(pdf.Uri);
// Save it over
var memOfPdf = new System.IO.MemoryStream();
pdfStream.CopyTo(memOfPdf);
var docsPath = System.Environment.GetFolderPat(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(docsPath, "temp.pdf");
System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray());
mainForms.DisplayThePDF(filePath);
}
}
this is only for PDF and also not working well.

Drag an image from table cell to an iFrame droppable area

I have problems to drag an image from one iframe (1) out of a dynamic table to another iframe (2) within a droppable area. I think there is no permission issue, but a "type" issue. The drop area on iframe (2) is working with files from anywhere except form the iframe (1). The iframe (1) is hosted by localhost. The iframe (2) is hosted by a different domain.
Three different functions I found to convert data uri to file or blob were tested. The setData arguments also have been tested with all possibilities, no success by now.
Interestingly, having opened the site with the two iframes on Chrome and firefox, I am able to drag an drop from firefox to Chrome, but the image will be converted to bmp type and renamed! The other way around it is not working.
What are the right arguments for setData / get Data to drop an image
data uri on a drop area?
Do I have to convert data uri to a file
resp. blob object?
If so, again, what arguments will do the job?
Any help would be appreciated very much!
var dataUri;
var file;
function mouseDown(event){
toDataURL(event.target.src, function(dataUrl) {
console.log('RESULT:', dataUrl.replace('data:text/plain;base64,', ''));
dataUri = dataUrl.replace('data:text/plain;base64,', '');
file = urltoFile(dataUrl, 'hello.jpg','image/jpeg')
.then(function(file){ console.log(file);});
})
}
function drag(event) {
// event.stopPropagation();
console.log(file);
console.log(dataUri);
event.dataTransfer.setData("text/plain", file);
//event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
event.dataTransfer.effectAllowed = "move";
}
function drop(event) {
//event.preventDefault();
console.log(file);
console.log(dataUri);
var data = event.dataTransfer.getData("text/plain");
//var data = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
event.target.appendChild(document.getElementById(data));
document.getElementsById(data);
console.log(data);
}
function allowDrop(event) {
event.preventDefault();
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var dw = new DataView(ab);
for(var i = 0; i < byteString.length; i++) {
dw.setUint8(i, byteString.charCodeAt(i));
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab], {type: mimeString});
}

I need to know how to add images from a files on my windows 10 PC to a google apps script HTML website

I want to add images to a google apps script hosted webpage.
I tried looking around the menus and checking google.
I want it to display the image at the desired size
Images from Albums in my Google Photo Library in a Web App
function doGet(e){
return displayAlbums(true);
}
//used for web app and dialog depending upon weather web parameter is true or not. If it's not provided then it's false.
function displayAlbums(web) {
var web=web||false;
//different color backgrounds for each album
var bgA=['#f3eeb3','#f3e2b3','#f3ceb3','#f3b3b6','#f3b3b6','#f3b3ef','#b3eaf3','#b3f3e3','#b3f3cb','#bdf3b3']
var html='';
var n=0;
var albumsA=listAlbums();
for(var i=0;i<albumsA.length;i++) {
html+='<html><head></head><body>';
html+=Utilities.formatString('<div id="d-%s" style="margin:auto;max-width:500px;background-color:%s;">',i,bgA[i]);
html+=Utilities.formatString('<h1>%s</h1>', albumsA[i].title);
var images=listImagesOfAnAlbum(albumsA[i].id);
for(var j=0;j<images.length;j++) {
html+=Utilities.formatString('<br />%s - %s<br /><img src="%s" width="500" />',j+1,images[j].filename, images[j].baseUrl);
}
html+='</div></body></html>';
}
if(!web) {
var userInterface=HtmlService.createHtmlOutput(html).setWidth(600).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Displaying my Albums');
}else{
var output=HtmlService.createHtmlOutput(html).setWidth(600).setHeight(500);
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}
}
function listAlbums() {
var token=null;
var fA=[];
var n=0;
do{
var params = {muteHttpExceptions:true,headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
var url=Utilities.formatString('https://photoslibrary.googleapis.com/v1/albums?pageSize=50%s',(token!=null)?"&pageToken=" + token:"");
var resp=UrlFetchApp.fetch(url,params);
var js=JSON.parse(resp.getContentText());
for(var i=0;i<js.albums.length;i++) {
fA.push({id:js.albums[i].id,title:js.albums[i].title,count:js.albums.mediaItemsCount});
}
token=js.nextPageToken;
}while(token!=null);
Logger.log(fA);
return fA;
}
function listImagesOfAnAlbum(albumId) {
var albumId= albumId || 'Default Id for debugging';
var token=null;
var iA=[];
var n=0;
do{
var params = {
method:"post",
muteHttpExceptions:true,
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
payload:{"albumId": albumId,"pageSize":"50","pageToken":token}};
var url="https://photoslibrary.googleapis.com/v1/mediaItems:search";
var resp=UrlFetchApp.fetch(url,params);
var js=JSON.parse(resp.getContentText());
for(var i=0;i<js.mediaItems.length;i++) {
iA.push({filename:js.mediaItems[i].filename,baseUrl:js.mediaItems[i].baseUrl});
}
token=js.nextPageToken;
}while(token!=null);
return iA;
}
Google Photos API
I added this to the manifest file:
"exceptionLogging": "STACKDRIVER",
"oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/photoslibrary", "https://www.googleapis.com/auth/script.container.ui", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/script.scriptapp", "https://www.googleapis.com/auth/spreadsheets"]
Also adding this to your google scripts even though you don't need it will provoke the authenticator to added the need scopes. And also setup the Drive API in Resources Advanced Google Services.
//DriveApp.getFiles();
function listFiles() {
var files = Drive.Files.list({
fields: 'nextPageToken, items(id, title)',
maxResults: 10
}).items;
for (var i = 0; i < files.length; i++) {
var file = files[i];
Logger.log('\n%s-Title: %s Id: %s',i+1,file.title,file.id);
}
}
This is a technique describe by Bruce McPherson as borrowing a Token you can read about it here
I had already loaded the Oauth2 and GOA libraries. According the Mr. McPherson you will need to install the GOA Library although I never actively used it. He has a walk through here Just go through his little slide presentation. This may seem like a lot of trouble and it is. But it does provide you with programmatic access to the photo library. Fortunately, Google does all this for us on most of our libraries.
From Your Personal Computer to your Website with DataURI's
Another way to get images right off of your Google Drive and into your webapp website.
The Javascript in the <script> tags of your website:
google.script.run
.withSuccessHandler(function(iObj){
console.log(iObj);
for(var i=0;i<iObj.iA.length;i++) {
if(i==iObj.iA.length-1) {
$('#header').css('background-image','URL(' + iObj[iObj.iA[i]] + ')');
}else{
$('#' + iObj.iA[i]).attr('src',iObj[iObj.iA[i]]);
}
}
})
.getSimpleSiteImages();
});
The Google Apps Script:
function getSimpleSiteImages() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('SimpleSite');
var rg=sh.getDataRange();
var vA=rg.getValues();
var oObj={iA:[]};
for(var i=0;i<vA.length;i++) {
oObj.iA[i]=vA[i][2];
oObj[oObj.iA[i]]=getDataURI(vA[i][1]);
}
return oObj;
}
function getDataURI(fileId) {
var file=DriveApp.getFileById(fileId);
return file.getBlob().getDataAsString();
}
The Google Apps Script That Makes the DataURI:
function convImageUrl(url){
var blob=UrlFetchApp.fetch(url).getBlob();
var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
return b64Url;
}
Just save on your google drive and upload them into your images.

Image created without filetype - need filetype for compression - Angular 2 / Ionic 3

I am trying to compress an image client-side (Angular 2/Ionic 3) and When I log the file that is created by the camera, it says:
"type":null when it should say "type":'image/jpeg'.
I am using the Ionic camera plugin to handle taking a picture or choosing one from the photo library, after that (I assume) the file is created without a type. Every compression tool I have tried has had this problem, and I have run out of options. Is there a way to change the type of a File object?
I created a new Blob with this method and made sure to give it image type:
dataURItoBlob(dataURI, callback): Promise<any> {
return new Promise((resolve, reject) => {
let byteString = atob(dataURI);
//console.log(byteString);
// separate out the mime component
//let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
let bb = new Blob([ab], {type: 'image/jpeg'});
resolve(bb);
})
}
I used it after reading the contents of the image to base64 like this and got the resulting blob with image type:
var readerZ = new FileReader();
readerZ.onload = (e) => {
let data = readerZ.result.split(',')[1];
//console.log(data);
self.dataURItoBlob(data, null).then(blob => {

AS3 URLRequest in for Loop problem

I read some data from a xml file, everything works great besides urls. I can't figure what's the problem with the "navigateURL" function or with the eventListener... on which square I click it opens the last url from the xml file
for(var i:Number = 0; i <= gamesInput.game.length() -1; i++)
{
var square:square_mc = new square_mc();
//xml values
var tGame_name:String = gamesInput.game.name.text()[i];//game name
var tGame_id:Number = gamesInput.children()[i].attributes()[2].toXMLString();//game id
var tGame_thumbnail:String = thumbPath + gamesInput.game.thumbnail.text()[i];//thumb path
var tGame_url:String = gamesInput.game.url.text()[i];//game url
addChild(square);
square.tgname_txt.text = tGame_name;
square.tgurl_txt.text = tGame_url;
//load & attach game thumb
var getThumb:URLRequest = new URLRequest(tGame_thumbnail);
var loadThumb:Loader = new Loader();
loadThumb.load(getThumb);
square.addChild(loadThumb);
//
square.y = squareY;
square.x = squareX;
squareX += square.width + 10;
square.buttonMode = true;
square.addEventListener(MouseEvent.CLICK, navigateURL);
}
function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
trace(tGame_url);
}
Many thanks!
In navigateURL() you use tGame_url, but I think you'd rather use something like tgurl_txt.text which will be different for each square.
Looks like you're not attaching the event listener properly. Instead of this.addEventListener, attach it to the variable you created when creating new square_mc..... so:
square.addEventListener(MouseEvent.CLICK, navigateURL);
you should add the addEventListener on the Squares
mmm..still figuring how eventhandler function will ever get the correct tgame_url var.
What if you try this:
square.addEventListener(MouseEvent.CLICK, function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
trace(tGame_url);
});
try tracing this:
function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
//trace(tGame_url);
trace(event.currentTarget.tgurl_txt.text);
}
you should add the url to your square in the loop
square.theUrl = tGame_url;
in the event listener function you should be able to access it with
event.currentTarget.theUrl;

Resources