Im working on a file upload in an ASP.net webpage with angular and wanted to ask how to check if the uploaded file is a pdf or jpg and has max 2MB. If this isn't the case there should be a sipmle text which is shown and the file should not be uploaded / listed on the file list. Can i do this in Frontend / Ts?
1 Answers
You can leverage the File API. Assuming you are using an <input>
of type file
, you can extract the files
property
To validate the field, perform this logic (inputRef
is a reference to the input
element, that may be retrieved by mean of document.getElementById
or any function provided by the framework you are using)
if (!inputRef.files || inputRef.files.length === 0) {
console.error("No files uploaded");
} else {
const file = inputRef.files[0];
if (['application/pdf', 'image/jpeg'].includes(file.type)) {
console.error('File should be a pdf or a jpeg');
} else if (file.size > 2e+6) {
console.error('File is too large. Over 2MB');
} else {
console.log('File is valid');
}
}
Please note that where size
can be trusted, type
is something that is derived by the extension hence if a user renames a file this check can still be avoided.
A warning on frontend validation
Use Frontend validation only to improve usability and never for security and integrity. You should check the file size and content on the backend. I sad content because the file extension (and derived MIME type) can never be trusted cause the file can be renamed.
As a general rule of thumb, you can avoid validating file content if the file isn't used by your server system (but only stored) and never presented to other users different than the uploader itself. Otherwise, the content may be corrupted (or even worse) and may deteriorate your system's usability.
Possible duplicate Here

- 4,462
- 11
- 23