Javascript How to convert Base 64 url to file?

Viewed 165

I am retriving file data from database, and I need to send to frontend (My frontend has download action to download the file) How to convert these type of url to file. I hope it can use in any file types (doc, txt, jpg, pdf, zip .....)

"data:text/plain;charset=utf-8;base64,MzQuNjIzNjU..................."

This is my implementation. It works on txt, but it does not work for jpg and other file types for some reasons. Can any one help me to figure out this problem? (I think it might be the encoding or decoding problem) Thanks :)

        let mime = file.url.split(',')[0].split(':')[1].split(';')[0];
        console.log(mime);
        let content = unescape(encodeURIComponent(file.url.split(',')[1]));
        content = Buffer.from(content, 'base64').toString();

        console.log(content);

        let temp = mime + ";charset=UTF-8";
        res.set('Content-Type', temp);
        res.set('Content-Disposition','attachment; filename=' + file.name );
        res.send(content);
2 Answers

You can use content = new Buffer(content, 'base64')

If you want to save it to a file, you can use this:

/* name is the name of the file you want to save your file in.*/
fs.writeFile(name , content, {encoding: 'base64'}, function(err){
  if (err) console.log('err', err);
  console.log('success');
});

Try with below hopefully this will work :-

 //return a promise that resolves with a File instance
    function urltoFile(url, filename, mimeType){
        return (fetch(url)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], filename,{type:mimeType});})
        );
    }
    
    //Usage example:
    urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')
    .then(function(file){ console.log(file);});

Related