1
1
import path from 'path'
2
+ import { FileValidationException } from './exception/file-validation.exception'
2
3
3
4
interface File {
4
5
fieldname : string
@@ -13,9 +14,11 @@ interface File {
13
14
}
14
15
15
16
/**
16
- * The function is used to validate the type of a file using the file extension and MIME type
17
+ * The function is used to validate the type of file using the file extension and MIME type
17
18
* @param file object that represent file
18
19
* @param cb callback function which indicates whether file is accepted or not
20
+ *
21
+ * @throws FileValidationException if the file does not pass validation
19
22
*/
20
23
export function validateFileType (
21
24
file : File ,
@@ -33,21 +36,27 @@ export function validateFileType(
33
36
'application/vnd.ms-excel' ,
34
37
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ,
35
38
]
39
+
40
+ let filename = file . originalname
41
+ let extension = path . extname ( filename ) . toLowerCase ( )
42
+ if ( extension == '' ) {
43
+ filename = file . filename
44
+ // for the expense files, the original filename is encoded in base64
45
+ extension = path . extname ( filename ) . toLowerCase ( )
46
+ }
47
+
36
48
if ( ! mimeAllowlist . includes ( file . mimetype ) ) {
37
- return cb ( new Error ( 'File mime type is not allowed' ) , false )
49
+ return cb ( new FileValidationException ( 'File mime type is not allowed' , filename ) , false )
38
50
}
39
51
40
52
const allowedExtensions = / t x t | j s o n | p d f | j p e g | j p g | p n g | x m l | x l s x | x l s | d o c x /
41
53
42
- const filename = file . originalname
43
- let ext = path . extname ( filename ) . toLowerCase ( )
44
- if ( ext == '' ) {
45
- // for the expense files, the original filename is encoded in base64
46
- ext = path . extname ( file . filename ) . toLowerCase ( )
47
- }
48
- const isExtensionSupported = allowedExtensions . test ( ext )
54
+ const isExtensionSupported = allowedExtensions . test ( extension )
49
55
if ( ! isExtensionSupported ) {
50
- return cb ( new Error ( 'File extension is not allowed: ' + file . filename ) , false )
56
+ return cb (
57
+ new FileValidationException ( 'File extension is not allowed: ' + filename , filename ) ,
58
+ false ,
59
+ )
51
60
}
52
61
53
62
cb ( null , true )
0 commit comments