seepur/app/Utils/FileUtils.js
2020-03-17 18:16:34 -04:00

40 lines
942 B
JavaScript

const Drive = use('Drive');
class FileUtils {
static async saveBase64File(base64Str) {
console.log(base64Str.length);
const parsed = parseBase64(base64Str);
const fileName =
`${Date.now()}-${Math.random() * 1000}.${parsed.extension}`;
const file = await Drive.put(fileName, parsed.data);
return {fileName, file};
}
static async getFile(filename) {
try {
return await Drive.get(filename)
} catch (e) {
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;