Nativescript: How to get photo list from gallery - javascript

The thing is I need to get photos from gallery automatically. I've read that ImagePicked is used to pick up photo from image store but it provides just in manual way (user does it by self).
Are there any opportunity get access to gallery, take list of photos and used them in an application?
Of course if are is it possible to filter them by criteria (get photos by date range)?

GingerComa, on Android you could try this:
import * from "file-system";
var tempPicturePath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DCIM).getAbsolutePath();
var folder : Folder = Folder.fromPath(tempPicturePath);
folder.getEntities()
.then(entities => {
// entities is array with the document's files and folders.
entities.forEach(entity => {
// console.log(entity.name);
// console.log(entity.path);
// console.log(entity.lastModified);
this.folderEntities.push(
new FolderEntity(entity.name, entity.path, entity.lastModified.toString())
);
});
}).catch(err => {
// Failed to obtain folder's contents.
console.log(err.stack);
});

Related

How to upload Bulk amount of json data with images to the firebase realtime and storage respectively

I have a bulk amount of data in CSV format. I am able to upload that data with python by converting them to the dictionary (dict) with loop. the whole data is getting uploaded.
but now I want to upload bulk data to firebase and images to storage and I want to link between each document and image because i am working on e-commerce react app. so that I can retrieve documents along with images.
which is a good way to do this? should I do this with javascript or python?
I uploaded data manually to firebase by importing from there but again I am unable to upload bulk images to storage and also unable to create references between them. please give me a source where I can find this solution
This is tough, because it's hard to fully understand how exactly your images and CSV's are linked, but generally if you need to link something to items stored in Firebase, you can get a link either manually (go into storage, click and item, and the 'Name' Field on the right hand side is a link), or you can get it when you upload it. So for example, I have my images stored in firebase, and a postgres database with a table storing the locations. In my API (Express), when I post the image to blob storage, I create the URL of the item, and post that as an entry in my table, as well as setting it to be the blobs name. I'll put the code here, but obviously it's a completely different architecture to your problem, so i'll try and highlight the important bits (it's also JS, not Python, sorry!):
const uploadFile = async () => {
var filename = "" + v4.v4() + ".png"; //uses the uuid library to create a unique value
const options = {
destination: filename,
resumable: true,
validation: "crc32c",
metadata: {
metadata: {
firebaseStorageDownloadTokens: v4.v4(),
},
},
};
storage
.bucket(bucketName)
.upload(localFilename, options, function (err, file) {});
pg.connect(connectionString, function (err, client, done) {
client.query(
`INSERT INTO table (image_location) VALUES ('${filename}')`, //inserts the filename we set earlier into the postgres table
function (err, result) {
done();
if (err) return console.error(err);
console.log(result.rows.length);
}
);
});
console.log(`${filename} uploaded to ${bucketName}.`);
};
Once you have a reference between the two like this, you can just get the one in the table first, then use that to pull in the other one using the location you have stored.

Sending and displaying images from Adonis V4.1

How can I send an image from a React App to Adonis, “save” it on the database, and when needed to fetch it to use in the front-end?
Right now, I was only successful in processing an image via Postman, my code would be like this:
const image = request.file('photo', {
types: ['image'],
size: '2mb',
});
await image.move(Helpers.tmpPath('uploads'), {
name: `${Date.now()}-${image.clientName}`,
});
if (image.status !== 'moved') {
return image.error;
}
/////
const data = {
username,
email,
role,
photo: image.fileName,
password,
access: 1,
};
const user = await User.create(data);
In the first part, I process the image move it to tmp inside the backend, on the next part I use image.fileName and create a User.
And when I need to fetch my user list, I do it like this:
const colaboradoresList = await Database.raw(
'select * from colaboradores where access = 1'
);
const userList = colaboradoresList[0];
userList.map((i) => (i.url = Helpers.tmpPath(`uploads/${i.photo}`)));
But as you can tell, Helpers.tmpPath('uploads/${i.photo}')) will return the local path to the current image, and I cannot display it on React since I need to use the public folder or download it and import.
Is there a way to do it locally, or the only way would be to create an AWS and use Drive.getUrl() to create a URL and send back to my front end?
Yes the UI cannot display local files, you need to expose a public url for the image. You have two options depending of the scope of this application
If you plan to run this as a professional app, I would highly suggest to use something like AWS S3 to store images.
Otherwise you can probably get away with setting up a route for the React UI to query. Something like /api/image/:id could return the binary or base64 encoded data of the image, which React could then display.
instead of
await image.move(Helpers.tmpPath('uploads'), {
name: `${Date.now()}-${image.clientName}`,
});
I use:
await image.move(Helpers.publicPath('uploads'),
{name: `${Date.now()}-${image.clientName}`})
For that you will need to change the folders to make it store correctly:
And then send to the front-end url = '/uploads/${i.photo}', where i.photo is the file name, so I can concatenate in React like so apiBase + url.
The result being your apiUrl + your file path that should be on public folder:

iterate through firebase storage to display multiple images

Currently I am able to fetch a specific picture knowing its title and location in the storage, but I want to be able to show all pictures in one folder inside my storage knowing the location of that storage folder but not the content titles.
I have tried using the below code (projectID is the folder which I need to show all the elements of) but it doesn't seem to work. I am new to javascript so I apologize for the wrong function call of .once.
const childRef = storageRefer.child(`${projectID}`);
childRef.once("value", function(snapshot) {
snapshot.forEach(function(child) {
child.getDownloadURL().then(function(url) {
console.log(url);
});
});
});
this code should be able to log the url of all the images but all I get is an error about the .once function. If anyone knows what I am doing wrong or a better method in getting all the images in one folder inside my storage that would be super helpful, thanks!
Edit:
Looking back at this I realized I could store the location of the images into a database for them as I can easily iterate through a database without knowing what is inside and call to storage to get the image, but that seems sloppy?
There currently is no API call in Firebase Storage to list all files in a folder. If you need such functionality, you should store the metadata of the files (such as the download URLs) in a place where you can list them. The Firebase Firestore is perfect for this and allows you to also easily share the URLs with others.
var listRef = firebase.storage().ref().child('profiles/');
listRef.listAll().then(function(res){
res.items.forEach(function(itemRef){
itemRef.getDownloadURL().then(function (link) {
console.log(link);
})
})
})
}
This function brings all photos saved in the storage "Profile"
I hope it works for you.
#Shodmoth Check out this new firebase link (https://firebase.google.com/docs/storage/web/list-files) for how to list all the files in a folder.
// Create a reference under which you want to list
var listRef = storageRef.child('files/uid');
// Find all the prefixes and items.
listRef.listAll().then(function(res) {
res.prefixes.forEach(function(folderRef) {
console.log(folderRef)
});
res.items.forEach(function(itemRef) {
console.log(itemRef) //can call .getDownloadURL() on each itemRef
});
}).catch(function(error) {
// Uh-oh, an error occurred!
});

AngularFire / Firestore - Return collections and documents as a service

I have several pages that reference the same node in firestore, each pulling different segments from the firestore node. For example, a summary page might pull through album title, date, genre and image, whilst another page might pull through just the title, artist and record label. A couple of questions:
Is it possible to turn one of the firestore queries into a service?
If so, does that mean the data is only read once whilst navigating across different pages (angular components) that use the same service?
Will the query only run again when data is modified in firestore through the observable? ("return Observable.create(observer => {" )
I have tried a service with the code below. However, the issue observed is that on page refresh, the data isn't present. It is however present whilst navigating through the site. I believe this is because my page is running before the observable is returned. Is there a way to wrap up the query as an observable?
Any assistance would be greatly appreciated.
getAlbumData() {
this.albumDoc = this.afs.doc(`albums/${this.albumId}`);
this.album = this.albumDoc.snapshotChanges();
this.album.subscribe((value) => {
// The returned Data
const data = value.payload.data();
// Firebase Reference
var storage = firebase.storage();
// If album cover exists
if (data.project_signature != undefined) {
// Get the Image URL
var image = data.album_cover_image;
// Create an image reference to the storage location
var imagePathReference = storage.ref().child(image);
// Get the download URL and set the local variable to the result (url)
imagePathReference.getDownloadURL().then((url) => {
this.album_cover = url;
});
}
});
}
When I build my observables, I try to use operators as much as I can until I get the data I want to display in my UI.
You don't want to implement too much code in the subscribe method because you break the reactive paradigm by doing so.
Instead, extract you data in your observable and display it in your template.
Don't forget to use the async pipe in your template to display your data when it gets fetched by your application.
I would do something like this:
// In AlbumService
getAlbumCover(albumId: string) {
const albumDoc = this.afs.doc(`albums/${albumId}`);
const album_cover$ = this.albumDoc.snapshotChanges().pipe(
// get the album data from firestore request
map(data => {
return {
id: data.payload.id,
...data.payload.data()
};
}),
// emits data only if it contains a defined project_signature
filter(album => album.project_signature),
// prepare the imagePath and get the album cover from the promise
mergeMap(album => {
const storage = firebase.storage();
const image = album.album_cover_image;
const imagePathReference = storage.ref().child(image);
return imagePathReference.getDownloadURL();
})
);
return album_cover$;
}
By doing so, when your data is updated in firestore, it will be fetched automatically by your application since you use an observable.
In your component, in the onInit() method after getting your album id from the url:
this.album_cover$ = this.albumService.getAlbumCover(albumId);
Finally, in my template, I would do :
<div>{{album_cover$ | async}}</div>

Insert pictures in Meteor

I just start learning Meteor. I put all my images in the root of "/public" folder. The images are named as "1.jpg","2.jpg","3.jpg".... I want to insert all the images to a collection "Images" by using for loop without putting a certain number as the for loop limit. So how can I make it detect how many images are in the public folder automatically?
You would need a mechanism to get the list of images in the public folder, using the fs package will do this for you. Consider the following example which uses the package to read the public directory which is /web.browser/app/ from the server (total unix path /home/user/your_app_name/.meteor/local/build/programs/web.browser/app/).
After getting the folder list, filter the list to only get image files with the extension .jpg, then insert the images to your collection. For illustrative purposes the image document saved to the collection has the following simple schema example
{ _id: "v2PrCTPea6tM6JNHn", name: "1.jpg" }
To aid you with your final goal of inserting the images to the mongo collection, you can use the batch-insert Meteor package which enables the underlying mongo driver to insert of multiple documents. It works just like insert() but takes an array of objects to be inserted rather than a single object.
#Installation
In your meteor app directory run:
meteor add mikowals:batch-insert
On server
var fs = Npm.require('fs'),
public_path = path.join(__meteor_bootstrap__.serverDir, "../web.browser/app"),
files = fs.readdirSync(public_path),
images = _(files).reject( function(fileName) {
return fileName.indexOf('.jpg') < 0;
}),
imagesList = images.map(function (image){
return { name: image };
});
Images = new Meteor.Collection('images');
Images.allow({
insert: function(){ return true };
});
var newIds = Images.batchInsert(imagesList); // returns array of created _id values

Categories