简体   繁体   中英

How to convert base64 string into file object in Javascript which should work in IE Browser

How to convert base64 string into file object in Javascript which should work in IE Browser

function dataURLtoFile(dataurl: any, filename: string) {
        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 });
}

This is not working in IE browser edge.

Add this:

<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>

This adds js compability into older browsers

After reading lots of tutorials I find a conclusion that Blob is also treated as File and we can post Blob into formdata.

var base64data = window.localStorage.getItem("img").replace("data:image/png;base64,", "");
        var bs = atob(base64data);
        var buffer = new ArrayBuffer(bs.length);
        var ba = new Uint8Array(buffer);
        for (var i = 0; i < bs.length; i++) {
            ba[i] = bs.charCodeAt(i);
        }
        var file = new Blob([ba], { type: "image/png" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM