Fix - Converting file types to media types
Check the file types correctly.
As was said before, the comparison is made not with file types (extensions), but with media types. For example, the file type "png" corresponds to the media type "image/png". So, the check succeeded merely due to coincidence. File types are not always included in their respective media types. To fix this, we'll use the mime-types library to get the media type of a file type. It is already installed, we just need the typing.
yarn add -D @types/mime-types
Above the createFileValidators()
function, we may create an auxiliary function that:
Obtains the media types from the
fileTypes
by using thelookup()
function from mime-typesCreates the regex for validating the media types
const createFileTypeRegex = (fileTypes: FileType[]) => {
const mediaTypes = fileTypes.map((type) => lookup(type));
return new RegExp(mediaTypes.join('|'));
};
Then, use it when creating the regex.
const fileTypeRegex = createFileTypeRegex(fileTypes);
Commit - Validating media types instead of extensions
Last updated