js写一个函数通过文件的MIME类型判断文件类型,兼容大部分文件类型

要写一个函数通过文件的MIME类型判断文件类型,你需要了解MIME类型与文件类型的对应关系。MIME类型是一种标准,用于表述文档、文件或字节流的性质和格式。下面是一个简单的JavaScript函数,该函数接收MIME类型作为参数,并返回对应的大致文件类型分类(例如:‘image’, ‘video’, ‘audio’, ‘document’ 等)。

请注意,以下函数并不完整,因为MIME类型的分类非常庞大,如果需要覆盖大部分文件类型,你可能需要扩展这个列表。你可以参考一些在线的MIME类型列表来完善这个函数。

function getFileTypeByMime(mimeType) {
    if (mimeType.startsWith('image/')) {
        return 'image';
    } else if (mimeType.startsWith('video/')) {
        return 'video';
    } else if (mimeType.startsWith('audio/')) {
        return 'audio';
    } else if (mimeType.startsWith('text/')) {
        return 'document';
    } else if (mimeType.startsWith('application/pdf')) {
        return 'document';
    } else if (mimeType.startsWith('application/msword') || mimeType.startsWith('application/vnd.openxmlformats-officedocument.wordprocessingml.')) {
        return 'document';
    } else if (mimeType.startsWith('application/vnd.ms-excel') || mimeType.startsWith('application/vnd.openxmlformats-officedocument.spreadsheetml.')) {
        return 'spreadsheet';
    } else if (mimeType.startsWith('application/vnd.ms-powerpoint') || mimeType.startsWith('application/vnd.openxmlformats-officedocument.presentationml.')) {
        return 'presentation';
    } else if (mimeType.startsWith('application/zip') || mimeType.startsWith('application/x-rar-compressed')) {
        return 'archive';
    } else if (mimeType.startsWith('application/json')) {
        return 'data';
    } else if (mimeType.startsWith('application/javascript')) {
        return 'code';
    } else if (mimeType.startsWith('application/xml')) {
        return 'code';
    } else if (mimeType.startsWith('multipart/form-data')) {
        return 'formData';
    } else {
        return 'unknown';
    }
}

console.log(getFileTypeByMime('image/jpeg')); // Outputs: image
console.log(getFileTypeByMime('video/mp4'));  // Outputs: video
console.log(getFileTypeByMime('application/vnd.ms-excel')); // Outputs: spreadsheet
// ... and so on for other MIME types

这个函数是一个起点,能够识别一些最常见的MIME类型对应的文件类型。根据需要,你可以增加更多的MIME类型判断,以适应你的具体场景。记住MIME类型有时候是不完全标准的,有些应用可能会使用自定义的MIME类型。

人工智能学习网站

https://chat.xutongbao.top

posted @ 2024-04-10 16:56  徐同保  阅读(2)  评论(0编辑  收藏  举报  来源