Creating a BLOB from a Base64 string in JavaScript

后端 未结 12 2892
说谎
说谎 2020-11-21 04:24

I have Base64-encoded binary data in a string:

const contentType = \'image/png\';
const b64Data = \'iVBORw0KGg         


        
12条回答
  •  萌比男神i
    2020-11-21 05:05

    For all copy-paste lovers out there like me, here is a cooked download function which works on Chrome, Firefox and Edge:

    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);
        });
    }
    

提交回复
热议问题