mime-type.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import path from 'path';
  2. import mime from 'mime-types';
  3. /**
  4. * 根据文件路径或名称的后缀获取 Content-Type
  5. * @param {string} filePath - 文件路径或名称
  6. * @returns {string} - Content-Type 或 'unknown'
  7. */
  8. export function getContentType(filePath) {
  9. const extension = path.extname(filePath); // 获取文件扩展名
  10. return getMimeType(extension);
  11. }
  12. /**
  13. * 根据扩展名返回 MIME 类型
  14. * @param {string} ext 文件扩展名
  15. * @returns {string} MIME 类型
  16. */
  17. export function getMimeType(ext) {
  18. // const mimeTypes = {
  19. // '.txt': 'text/plain; charset=utf-8',
  20. // '.html': 'text/html; charset=utf-8',
  21. // '.css': 'text/css; charset=utf-8',
  22. // '.js': 'application/javascript; charset=utf-8',
  23. // '.json': 'application/json; charset=utf-8',
  24. // '.jpg': 'image/jpeg',
  25. // '.jpeg': 'image/jpeg',
  26. // '.png': 'image/png',
  27. // '.gif': 'image/gif',
  28. // '.svg': 'image/svg+xml',
  29. // '.pdf': 'application/pdf',
  30. // };
  31. // return mimeTypes[ext] || 'application/octet-stream';
  32. const mimeType = mime.lookup(ext); // 从扩展名获取 MIME 类型
  33. const isUtf8Type = (mimeType && mimeType.includes('text')) || ext.includes('.js'); // 文本类的加; charset=utf-8
  34. const extInfo = (mimeType && isUtf8Type) ? '; charset=utf-8' : '';
  35. return (mimeType || 'application/octet-stream') + extInfo; // 如果未匹配,返回 'unknown'
  36. }