js base64转file文件

先上代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>base64转file</title>
</head>
<img class="img" id="img" width="200" height="200" src="234.png" alt="">
<canvas id="canvas" width="1000" height="1000"></canvas>
<body>
    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const img = document.getElementById('img');
        
        // img加载完成
        img.onload = function () {
            ctx.drawImage(img, 10, 10)
        }
        
        // canvas转base64
        base64Data = canvas.toDataURL('image/jpg');

        // base64转blob
        const base64ToBlob = function(base64Data) {
            let arr = base64Data.split(','),
                fileType = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                l = bstr.length,
                u8Arr = new Uint8Array(l);
                
            while (l--) {
                u8Arr[l] = bstr.charCodeAt(l);
            }
            return new Blob([u8Arr], {
                type: fileType
            });
        };
        // blob转file
        const blobToFile = function(newBlob, fileName) {
            newBlob.lastModifiedDate = new Date();
            newBlob.name = fileName;
            return newBlob;
        };
        // 调用
        const blob = base64ToBlob(base64Data);
        const file = blobToFile(blob, '123');
    </script>
</body>
</html>

由于项目需要将base64转换为file文件上传到服务器 正常使用new File()就可以了 使用后发现ios系统有兼容问题 后来一顿搜索 找到了一个曲线救国的方法 就是 base64 ->blob->file 这样就能解决ios的兼容问题了

atob(ascii to binary) 是window对象的函数,用于将ascii码解析成binary数据。
Uint8Array 数组类型表示一个8位无符号整型数组,创建时内容被初始化为0。创建完后,可以以对象的方式或使用数组下标索引的方式引用数组中的元素。

猜你喜欢

转载自www.cnblogs.com/ruir/p/12100483.html