Js图片、文件转 base64|转 bob (前端)

in 前端JavaScript with 0 comment

Js图片、文件转 base64|转 bob (前端)

将图片转 base64 | 或者文件转 base64

// 图片文件转为 base64
const fileConvertBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
};
这里提供一些简单的实例

将图片或者文件转 bob

将 file 文件转 Blob

const loadFileBob = file => {
    let base64,
        reader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onloadend = async function (e) {
            base64 = e.target.result;
            var arr = base64.split(','),
                mime = arr[0].match(/:(.*?);/)[1];
            resolve({ base64, fileType: mime });
        };
        reader.readAsDataURL(file);
    });
};

将 base64 转 Blob

# 代码
function base64ToBlob(code) {
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;

    let uInt8Array = new Uint8Array(rawLength);
    console.log(uInt8Array);
    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], { type: contentType });
}

获取扩展名 | ConenetType

// 获取扩展名
const getFileExtension = filename => {
    const _filename = filename.split('.');
    return _filename[_filename.length - 1];
};

// 获取文件类型ConenetType
// 这里只列出常见的几种
// 详情参考 https://surest.cn/archives/203/
const ContentTypeMap = {
    jpeg: 'image/jpeg',
    jpg: 'image/jpeg',
    png: 'image/png',
    gif: 'image/gif',
    mp4: 'video/mpeg4',
    ppt: 'application/vnd.ms-powerpoint',
    pdf: 'application/pdf',
    txt: 'application/txt',
};
const getUploadFileContentType = file => {
    const ext = getFileExtension(file);
    const type = ContentTypeMap.ext ?: '';
    if (!type) return;

    return type;
};
Comments are closed.