interface FileItem { fileId: string fileName: string byteCount: string sizeText: string extensionName: string type: string previewShow: boolean [key: string]: any } interface FileList { fileId: string fileName: string byteCount: number extensionName: string [key: string]: any } // 视频格式 const vidoeTypes = ['mp4', 'mov', 'avi', 'mkv', 'wmv', 'flv', 'mpeg', 'mpg', '3gp', 'webm'] // 文档格式 const docTypes = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'rtf', 'pdf'] // 图像文件 const imageTypes = ['jpg', 'png', 'bmp', 'gif'] /** * @description: 文件类型是否支持预览 * @param {string} extensionName 文件后缀 * @return {boolean} 是否支持预览 */ export const filePreviewShow = (extensionName: string) => { const suffix = extensionName.replace(/\./g, '').toLowerCase() if (vidoeTypes.includes(suffix)) { return true } else if (docTypes.includes(suffix)) { return true } else if (imageTypes.includes(suffix)) { return true } else { return false } } /** * @description: 文件类型 * @param extensionName 文件后缀 * @returns {string} */ export const fileType = (extensionName: string) => { const suffix = extensionName.replace(/\./g, '').toLowerCase() if (vidoeTypes.includes(suffix)) { return 'video' } else if (docTypes.includes(suffix)) { return 'doc' } else if (imageTypes.includes(suffix)) { return 'image' } else { return 'other' } } /** * @description: 文件大小格式化 * @param size 文件后缀 * @returns {string} */ export const fileSizeFormat = (size: number) => { const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] let i = 0 while (size >= 1024) { size /= 1024 i++ } return `${size.toFixed(2)} ${units[i]}` } /** * @description: 文件列表格式化 * @param fileList 文件列表 * @returns {FileItem[]} 文件列表 */ export const fileListFormat = (fileList: FileList) => { const result: FileItem[] = [] for (let i = 0; i < fileList.length; i++) { const file = fileList[i] const { fileId, fileName, byteCount, extensionName } = file const type = fileType(extensionName) const previewShow = filePreviewShow(extensionName) result.push({ fileId, fileName, sizeText: fileSizeFormat(byteCount), byteCount, type, previewShow, extensionName }) } return result }