I am working with React & Typescript and want to add validation logic when uploading image files. It accepts up to 2 images and 10 Megabyte (sum of 2 images) is the maximum size that user can upload.
I currently have below code to validate the above logic but I am confused if my unit comparison is correct.
const onFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectableMaxFileSize = 1024 * 1024 * 10 // 10 Megabyte
let initialFileSize: number = 0
if (e.target.files) {
for (let i = 0; i < e.target.files.length; i++) {
const file = e.target.files[i]
initialFileSize += file.size
}
if (initialFileSize > selectableMaxFileSize) {
setHasModal(true)
e.target.value = ''
return
}
Also I noticed I can simply access to file size by e.target.size, then compare with selectableMaxFileSize - does this work as well?