Insert pictures in Meteor - javascript

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

Related

How to return an absolute path if i have only a relative path in NestJS?

I have a NestJS project with a typeORM driver (MySQL). When a user uploads a photo then the server saves file in public directory and saves a relative path in DB: /public/user22.png
When a user sends a request for getting info about their profile, the server should return an absolute path.
Also a user can get a list of users.
I can edit the returning object for the user profile. But i don't want to use cycle for editing the list of users. Are there any optimal algorithms to solve the issue?
You have two solutions to transform your relative path to an absolute path.
First option is to append every image used in your front-end based on an environment variable called apiBaseUrl for example.
const users = await axios.get('/users');
<img src={`${process.env.NEXT_PUBLIC_API_BASEURL}/${users.image}`}/>
It will start to be unoptimized if you'r using this many times of course.
Second option is to create modify before returning your result to modify your photo value with an environment variable called baseUrl for example.
const result: exampleEntity = this.exampleRepository.find();
const newExample: exampleEntity = this.exampleRepository.create({
...result,
photo: this.configService.baseUrl + result.photo,
});
return entityExample;
If you don't handle environment variables for the moment, you can read the configuration documentation

Meteor: How to store and retrive file in a mongodb collection?

I try to save the content of uploaded file in a collection:
export const Files = new Mongo.Collection('files');
Meteor.methods({
'saveFileToDB': function (buffer) {
Files.insert({ data:buffer,
createdAt: new Date(),
owner: this.userId,
username: Meteor.users.findOne(this.userId).username
});
},
});
In another file I want to retrieve the saved file. First, I don't know what id I should to pass it. Suppose that there is one file in the collection or I want the first one, or the ones owned by the current user. I tried, I passed fileId as 1 but it didn't work. I don't know actually the question marks below:
import {Files} from "./files";
Meteor.methods({
'slides.readFileFromDB'(fileId) {
if (Files.???) { //contain any data
const text = Files.findOne(???);
console.log(text);
// Meteor.call('slides.insert', text);
return text;
}
})
});
There is a special layer for storing files as chunks, called GridFs because a normal collection will get into problems when you try to store binaries larger than 16MB.
There is also a well established wrapper for handling files in Meteor. Check out the following package: https://github.com/VeliovGroup/Meteor-Files

Nativescript: How to get photo list from gallery

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);
});

Add a custom property to GridFS Meteor FS file during upload

I'm currently creating a file upload and display feature for a web app.
I need to add a custom property (e.g accountID) so that I can later display only the images belonging to a specific account.
I'm using cfs:standard-packages with gridfs to upload/store my images.
I believe I need to add a beforeWrite function to the FS.Store but am unsure how to go about it.
The easiest way to do this is to immediately update the inserted object as follows:
var fileId = MyFiles.insert(file);
MyFiles.update({ _id: fileId },{ $set: { accountId: myAccountId }});
Note that the actual upload of the file object to the store will be asynchronous but you'll get the _id back synchronously and immediately.

Remove all files from Mongo GridFs (both files and chunks)

I'm writing some tests agains MongoDb GridFs and want to make sure that I start each test with a clean slate. So I want to remove everything, both from fs_files and fs_chunks.
What's the easiest way to do that?
If GridFs has its own database then I would just drop the database via mongo shell with db.dropDatabase(). Alternately if there are collections you would like to keep apart from fs_files and fs_chunks in the database you could drop the collections explicitly with db.collection.drop(). For both you can run via command from a driver rather than through the shell if desired.
If you want to remove GridFS, try it like (pyMongo Case)
for i in fs.find(): # or fs.list()
print fs.delete(i._id)
The simple way to remove all files and chunks is
let bucket = new GridFSBucket(db, { bucketName: 'gridfsdownload' });
bucket.drop(function(error) { /* do something */ });
This will remove the collections as well. If you want to keep the collections, you need to
to do something like this:
let allFiles = db.collection('uploaded.file').find({}).toArray();
for (let file of allFiles) {
await bucket.delete(file._id);
}

Categories