2020-03-17 22:16:34 +00:00
|
|
|
const Drive = use('Drive');
|
|
|
|
|
|
|
|
|
|
|
|
class FileUtils {
|
2020-05-24 19:59:44 +00:00
|
|
|
static async saveBase64File(base64Str, _fileName = null) {
|
2020-03-17 22:16:34 +00:00
|
|
|
console.log(base64Str.length);
|
|
|
|
const parsed = parseBase64(base64Str);
|
2020-05-24 19:59:44 +00:00
|
|
|
const fileName = _fileName ||
|
2020-03-17 22:16:34 +00:00
|
|
|
`${Date.now()}-${Math.random() * 1000}.${parsed.extension}`;
|
2020-05-24 19:59:44 +00:00
|
|
|
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) {
|
2020-04-29 23:45:50 +00:00
|
|
|
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;
|