Home > Net >  How to create a blob from a base64 string; javascript
How to create a blob from a base64 string; javascript

Time:06-06

Basically what the title says; I have a base64 string that encodes an image and I want to convert it into a blob so I can pass it into my File constructor. I realise many similar questions have been asked however many of the other answers make use of the atob function which has been deprecated; So im trying to look for alternatives.

CodePudding user response:

Try this

var base64String = "dGVzdAo=";
var blob = new Blob([base64String], {type: 'text/plain'});

CodePudding user response:

Found this solution in other question, hope this will help you, this apparently works on every browser.

window.saveFile = function (bytesBase64, mimeType, fileName) {
    var fileUrl = "data:"   mimeType   ";base64,"   bytesBase64;
    fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
        var link = window.document.createElement("a");
        link.href = window.URL.createObjectURL(blob, { type: mimeType });
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

There's a bunch of solutions avoiding using atob, I picked you the one that uses fetch method, based on avoiding certain scenarios which it can't work other solutions for more visit Creating a BLOB from a Base64 string in JavaScript

  • Related