base64转blob并下载文件

需求

支持文件转为base64,base64转blob,blob下载为文件

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>base64 to file</h2>
    <textarea name="" id="text-area" cols="30" rows="10" style='width:100%;height: 200px;' placeholder="Paste base64 string here"></textarea>
    <button class="download-btn" style='width: 150px;height:50px;display: block;margin:10px auto;'>Download</button>
    <script>

            /**
            * 上传附件转base64
            * @param {File} file 文件流
            */
            const fileByBase64 = (file, callback) => {
                var reader = new FileReader();
                // 传入一个参数对象即可得到基于该参数对象的文本内容
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    // target.result 该属性表示目标对象的DataURL
                    console.log(e.target.result);
                    callback(e.target.result)
                };
            }
            /**
            * base64转Blob
            * @param {*} data 
            */
            const base64ByBlob = (base64, callback) => {
                var arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                console.log(new Blob([u8arr], { type: mime }))
                callback(new Blob([u8arr], { type: mime }))
            }

            document.querySelector('.download-btn').addEventListener('click',function(e) {
                const base64 = document.querySelector('.text-area').inneerText;

                // fileByBase64(file, (base64) => {
                    base64ByBlob(base64, (blob) => {
                    // var url = window.URL.createObjectURL(blob)


                    const fileName = `${new Date().valueOf()}.txt`;
                    const link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                    window.URL.revokeObjectURL(link.href);
                })
                // })

            })


    </script>
</body>
</html>

发表评论