Files
PrivyDrop/frontend/lib/fileUtils.ts
T
2025-06-07 16:10:45 +08:00

34 lines
1.1 KiB
TypeScript

import { CustomFile } from '@/types/webrtc';
//对文件大小自适应单位并格式化输出
export const formatFileSize = (sizeInBytes: number): string => {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = sizeInBytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
};
export const generateFileId = (file: CustomFile): string => {
return `${file.fullName}-${file.size}-${file.type}-${file.lastModified}`;
};
/**
* Triggers a browser download for the given file-like object.
* @param file - The file blob or any file-like object that can be used with URL.createObjectURL.
* @param saveName - The name to use for the downloaded file.
*/
export const downloadAs = async (file: Blob | File, saveName: string): Promise<void> => {
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.href = url;
a.download = saveName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};