zpy-tools
Version:
提供了日期格式化、日期计算、文件格式化、本地缓存处理、Base64转File、File转Base64、节流防抖、数组排序、数据结构转化、深度比较两个对象是否包含相同的值等相关功能
132 lines (115 loc) • 3.78 kB
JavaScript
/**
* 将文件大小从一个单位转换为另一个单位
*
* @param {Number} size - 文件大小,以字节为单位
* @param {String} fromUnit - 当前文件大小单位,可选值:'B'、'KB'、'MB'、'GB'、'TB'
* @param {String} toUnit - 目标文件大小单位,可选值:'B'、'KB'、'MB'、'GB'、'TB'
* @param {Number} [decimalPoint=2] - 保留小数位数,默认为2
* @returns {Number} -转换后的文件大小,以目标单位为单位
*/
function fileSizeConvert(size, fromUnit, toUnit, decimalPoint = 2) {
try {
let units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB"];
let fromIndex = units.indexOf(fromUnit);
let toIndex = units.indexOf(toUnit);
// 如果单位不在列表中,抛出错误
if (fromIndex === -1 || toIndex === -1) {
throw new Error("Invalid unit");
}
// 计算初始单位和目标单位的转换系数
let exponent = toIndex - fromIndex;
// 计算结果大小
let resultSize = size / Math.pow(1024, exponent);
// 返回格式化后的结果
return resultSize.toFixed(decimalPoint) + " " + toUnit;
} catch (e) {
console.error("Error Convert file size:", e);
return null;
}
}
/**
* 将一个文件从小单位转换为大单位
*
* @param {Number} size - 文件大小,以KB为单位
* @returns {String} - 格式化后的文件大小,以大单位为单位
*/
function fileSizeFormat(size, decimalPoint = 2) {
try {
let units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB"];
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
unitIndex++;
size = size / 1024;
}
return size.toFixed(decimalPoint) + " " + units[unitIndex];
} catch (e) {
console.error("Error Format file size:", e);
return null;
}
}
/**
* File 文件转 Baes64
* @param {File} file 文件
* @returns {string} base64 字符串
*/
function fileToBase64(file) {
return new Promise((resolve, reject) => {
// 确保文件存在
if (!file) {
reject(new Error("File is missing."));
return;
}
// 创建一个 FileReader 对象
const reader = new FileReader();
// 定义读取完成的回调
reader.onload = function (e) {
// e.target.result 将会是 data:URL,即 base64 编码的文件内容
const base64Data = e.target.result;
// resolve(base64Data.split(',')[1]); // 移除"data:image/*;"前缀
resolve(base64Data);
};
// 定义读取失败的回调
reader.onerror = function (error) {
reject(error);
};
// 开始读取指定的Blob或File对象
reader.readAsDataURL(file);
});
}
/**
* Baes64 文件转 File
* @param {String} base64 base64字符串
* @returns {File} File 对象
*/
function base64ToFile(base64, fileName) {
// 1,将base64转换为blob
var blob = dataURLtoBlob(base64);
// 2,再将blob转换为file
var file = blobToFile(blob, fileName);
return file;
}
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 blobToFile(blob, fileName) {
blob.lastModifiedDate = new Date(); // 文件最后的修改日期
blob.name = fileName; // 文件名
return new File([blob], fileName, {
type: blob.type,
lastModified: Date.now(),
});
}
module.exports = {
fileSizeConvert,
fileSizeFormat,
fileToBase64,
base64ToFile,
};