0
点赞
收藏
分享

微信扫一扫

js文件相关操作

玉新行者 2022-03-11 阅读 59

 //base64转化为blob
    dataURLtoBlob(dataurl: string) {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }

    //转换为文件
    dataURLtoFile(dataurl: string, filename: string) {
        const arr = dataurl.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }

    //下载blob
    downloadBlob(blob: any, fileName: string) {
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = fileName;
        a.click();
        URL.revokeObjectURL(a.href);
        a.remove();
    }

    //file转化为base64
    fileToBase64(file: UploadFile, success: (base64: string, e: any) => void) {
        const reader = new FileReader()
        reader.readAsDataURL(file as any)
        reader.onloadend = (e: any) => {
            const base64 = e.target.result
            success(base64, e)
        }
    }
举报

相关推荐

0 条评论