JSFiddle - React, Tailwind, and code Playground
by Evgeniy Kvasyuk
TypeScript
// Define the Asset type
type Asset = {
filename: string;
};
// Define a robust mapping of file extensions to MIME types.
const mimeTypes: { [key: string]: string } = {
"png": "image/png",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"gif": "image/gif",
"webp": "image/webp",
"pdf": "application/pdf",
"txt": "text/plain",
"html": "text/html",
"json": "application/json",
"jfif": "image/jpeg", // Support for .jfif images
"svg": "image/svg+xml", // Support for .svg images
// Document formats
"doc": "application/msword",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ppt": "application/vnd.ms-powerpoint",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"odt": "application/vnd.oasis.opendocument.text",
"ods": "application/vnd.oasis.opendocument.spreadsheet",
// Video formats
"mp4": "video/mp4",
"avi": "video/x-msvideo",
"mov": "video/quicktime",
"mkv": "video/x-matroska",
"flv": "video/x-flv",
"wmv": "video/x-ms-wmv",
// Audio formats
"mp3": "audio/mpeg",
"wav": "audio/wav",
"ogg": "audio/ogg",
"flac": "audio/flac",
"aac": "audio/aac",
"wma": "audio/x-ms-wma",
// Add more audio formats as needed.
};
function getContentType(asset: Asset): string {
const filename = asset.filename;
// Find the last period which should precede the extension
const extStart = filename.lastIndexOf('.');
if (extStart === -1) {
return 'application/octet-stream'; // Default to binary stream if no valid extension found
}
// Extract the extension, stopping at any hyphen if it exists
const hyphenIndex = filename.indexOf('-', extStart);
const extension = hyphenIndex !== -1 ?
filename.substring(extStart + 1, hyphenIndex) :
filename.substring(extStart +...