Closed Majunko closed 3 years ago
@Majunko
assuming user.enitry.ts
User modal is in use, where you can create simple method profilePicAsDataString
which in case wrap your logic.
this use case is not directly useful at framework core, its more like application level utility
No problem, i created a service with 2 functions to make this.
getPathLocalDisk(path: string): string {
const directory = Config.getOrThrow(
'settings.disk.local.directory',
'string',
'You must provide a directory name when using local file storage (LocalDisk).'
);
return join(directory, path);
}
fileToBase64(file: string): string {
try {
const binaryData = fs.readFileSync(this.getPathLocalDisk(file));
const base64String = Buffer.from(binaryData).toString('base64');
return base64String;
} catch (e) {
console.error(e);
}
return '';
}
So i call it like this:
const users = await getRepository(User)
.createQueryBuilder('user')
.select(['user.id', 'user.name', 'user.email', 'user.profile_photo'])
.getMany();
users.forEach(element => {
element['profilePhotoB64'] = this.myService.fileToBase64(element.profile_photo);
});
@Majunko why not using the Disk
service directly?
class FileService {
@dependency
disk: Disk;
async readFile() {
const { file, size } = await this.disk.read('avatars/xxx.jpg', 'buffer');
return file.toString('base64');
}
}
My mistake, more simple and readable. It works pretty well.
Thank you so much for your reply.
Hello,
i'm currently working this FoalTS and Angular, so i would like that FoalTS has a function that allows read a file with the actual function read() and create another function to convert this file readed to base64.
I made this with the next code:
I don't know if there is a better way to do this, but this is what i need when i read many users with his profile photos. Regards.