Skip to content

Instantly share code, notes, and snippets.

@angeldelacruzdev
Created February 28, 2023 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angeldelacruzdev/b37e3615b2afcf8b72b093a215b5422f to your computer and use it in GitHub Desktop.
Save angeldelacruzdev/b37e3615b2afcf8b72b093a215b5422f to your computer and use it in GitHub Desktop.
var crypto = require('crypto');
var seed = crypto.randomBytes(20);
var uniqueSHA1String = crypto.createHash('sha1').update(seed).digest('hex');
var imageTypeRegularExpression = /\/(.*?)$/;
var imageBuffer = this.decodeBase64Image(createSlideshowDto.base64);
var imageTypeDetected = imageBuffer.type.match(imageTypeRegularExpression);
var data = createSlideshowDto.base64.replace(
/^data:image\/\w+;base64,/,
'',
);
console.log(data);
fs.writeFile(
`./files/base64-${uniqueSHA1String}.${imageTypeDetected[1]}}`,
data,
{ encoding: 'base64' },
function (err) {
//Finished
console.log(err);
},
);
decodeBase64Image(dataString: string) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response: any = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = Buffer.from(matches[2], 'base64').toString('utf8');
console.log(response);
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment