I have a very simple validation pipe for accepting MS Word and PDF files.
@UploadedFile(
new ParseFilePipe({
validators: [
new FileTypeValidator({ fileType: '.(doc|docx|pdf)' }),
],
}),
)
Everything works, and all files validating correctly, but eventually I got this error:
Validation failed (current file type is application/msword, expected type is .(doc|docx|pdf))
I tried to make Regex or add application/msword to fileType string, but nothing works.
Maybe the file is corrupted?
There are two problems:
First, fileType property expects a mime-type, and you're providing a file extension (even though you mention you already tried it, adding it because it's not in your code snippet):
FileTypeValidator- Checks if a given file's mime-type matches a given string or RegExp. By default, validates the mime-type using file content magic numberhttps://docs.nestjs.com/techniques/file-upload#file-validation
so, use mime-type of doc|docx|pdf extensions:
fileType: /^(application\/msword|application\/vnd\.openxmlformats-officedocument\.wordprocessingml\.document|application\/pdf)$/i
Second, nest.js uses file-type which detects the file type by checking the magic number of the buffer. That may fail in some cases, so you can add fallback to mime type string checking:
fallbackToMimetype: true
or disable magic numbers check:
skipMagicNumbersValidation: true
see:
/**
* Fallback logic: If file-type cannot detect magic number (e.g. file too small),
* Optionally fall back to mimetype string for compatibility.
* This is useful for plain text, CSVs, or files without recognizable signatures.
*/
if (this.validationOptions.fallbackToMimetype) {
return !!file.mimetype.match(this.validationOptions.fileType);
}