Attacler/Bart
Attacler/Bart2y ago

How can i return a base64 as file on Deno Deploy?

Could someone give me an example for this?
7 Replies
ioB
ioB2y ago
can you explain what you’re trying to do?
ioB
ioB2y ago
I think this might be a https://xyproblem.info
The XY Problem
Asking about your attempted solution rather than your actual problem
Attacler/Bart
Attacler/BartOP2y ago
I already found it, i basicly have to transform the base64 string into a file and then just provide it in the new Response 🙂
ioB
ioB2y ago
Could you share code for your solution? This may be useful to people in the future looking for how to do this as well...
Attacler/Bart
Attacler/BartOP2y ago
Sure:
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);

while(n--){
u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, {type:mime});
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);

while(n--){
u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, {type:mime});
}
The first argument would be your base64 string, then it gets converted to the image using the second parameter as filename. Then inside of your deploy function you can use:
return new Response(dataURLtoFile(base64Image,"file.name"));
return new Response(dataURLtoFile(base64Image,"file.name"));
This will return the file to the visitor of your deno deploy project
ioB
ioB2y ago
cool! thanks for sharing!
Attacler/Bart
Attacler/BartOP2y ago
no problem! the function dataURLtoFile comes somewhere from stackoverflow

Did you find this page helpful?