This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
seepur/app/Utils/FileUtils.js

43 lines
1 KiB
JavaScript
Raw Normal View History

2020-03-17 22:16:34 +00:00
const Drive = use('Drive');
class FileUtils {
static async saveBase64File(base64Str, _fileName = null) {
2020-03-17 22:16:34 +00:00
console.log(base64Str.length);
const parsed = parseBase64(base64Str);
const fileName = _fileName ||
2020-03-17 22:16:34 +00:00
`${Date.now()}-${Math.random() * 1000}.${parsed.extension}`;
console.log(fileName);
2020-03-17 22:16:34 +00:00
const file = await Drive.put(fileName, parsed.data);
return {fileName, file};
}
static async getFile(filename) {
try {
return await Drive.get(filename)
} catch (e) {
console.error(e);
2020-03-17 22:16:34 +00:00
return null;
}
}
}
function parseBase64(dataString) {
const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
if (matches.length !== 3) {
return new Error('Invalid input string');
}
let extension = matches[1].split('/')[1];
// if (extension === 'jpeg') extension = 'jpg';
let data = matches[2];
console.log(data[0], data[1]);
return {
type: matches[1], extension, data: Buffer.from(data, 'base64'),
}
}
module.exports = FileUtils;