JS实现将文件和base64的相互转换

  • Post author:
  • Post category:其他

1. JS将文件转成base64

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JS将文件转成base64</title>
    <style></style>
</head>
<body>
    <input type="file" id="fielinput" />
    <script>
    
        window.onload = function () {
            // 获取文件dom
            var input = document.getElementById("fielinput");
            // 判断该浏览器是否支持FileReader
            if (typeof (FileReader) === 'undefined') {
                console.log("你的浏览器不支持 FileReader");
                input.setAttribute('disabled', 'disabled');
            } else {
                // 为file添加事件监听
                input.addEventListener('change', parseFileToBase64, false);
            }
        }
        
        // 获取文件对象并转换成base64
        function parseFileToBase64() {
            // 获取到文件对象
            var file = this.files[0];
            // 获取FileReader实例
            var reader = new FileReader();
            // 将文件加载进入
            reader.readAsDataURL(file);
            reader.onload = function (e) { 
                // 转换完成输出该文件base64编码
                console.log(this.result);
            }
        }
     
    </script>
</body>
</html>

2. JS将base64转成文件,并进行下载获取

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS将base64转换成文件并下载获取</title>
<style>
</style>
<script>
    
    function dataURLtoBlob(dataurl) {
        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 Blob([u8arr], { type: mime });
        }
 
    function downloadFile(url,name='文件默认名'){
        var a = document.createElement("a")
        a.setAttribute("href",url)
        a.setAttribute("download",name)
        a.setAttribute("target","_blank")
        let clickEvent = document.createEvent("MouseEvents");
        clickEvent.initEvent("click", true, true);  
        a.dispatchEvent(clickEvent);
    }
 
    function downloadFileByBase64(base64,name){
        var myBlob = dataURLtoBlob(base64)
        var myUrl = URL.createObjectURL(myBlob)
        downloadFile(myUrl,name)
    }
    
    var yourBase64 = '输入文件base64编码'
    var youFileName = '输入你的文件名'
    downloadFileByBase64(yourBase64, youFileName)
</script>
</head>
<body>
</body>
</html>

如果需要将整个文件夹全部转换成base64,可以将该文件夹压缩,然后按上述方法将该压缩文件转换成base64,将该base64转成压缩文件时,注意它的名称定义,应定义成 ***.zip。同理你若转换的是txt文件,那名称定义时应定义为 ***.txt。所以你将什么类型的文件转成base64,那么你将该base64转成文件时,名称的后缀名要保持不变。


版权声明:本文为chen1042246612原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。