So the thing that's happening I am kind of stuck with the extensions of fileApi, I can't see to figure out how should I display the alert when the Upload file is not .pdf
for example. I would really love some guidance. Thanks
Html
<form action="/Document" method="post" enctype="multipart/form-data">
<div >
<div style="margin-top: 25px; margin-bottom: 15px;">
<input type="file" id="validatedCustomFile" name="document" required>
<div style="color: red;"></div>
</div>
<div >
<ul>
<li>Maximum upload size is / 1024) KB</li>
</ul>
</div>
<div>
<button type="submit" title="Next" >Next</button>
</div>
</div>
</form>
<script>
Js
const InputFile = document.getElementById('validatedCustomFile');
InputFile.addEventListener("change", function () {
console.log(InputFile.files)
for (const file of InputFile.files) {
if (file.size > 1048576){
alert(`${file.name} is to big! Max is 1024KB`);
}
if (file.type != '.pdf') {
alert('This file type not allowed to be uploaded')
}
}
}
)
</script>
CodePudding user response:
here, you need to set mime type of file . Here, I have mention application/pdf instead of ".pdf"
const InputFile = document.getElementById('validatedCustomFile');
InputFile.addEventListener("change", function () {
console.log(InputFile.files)
for (const file of InputFile.files) {
if (file.size > 1048576){
alert(`${file.name} is to big! Max is 1024KB`);
}
if (file.type != 'application/pdf') {
alert('This file type not allowed to be uploaded')
}
}
}
)
CodePudding user response:
There is a simple method to it, by just adding to your form input accept=".pdf"
The upload page is only going to display the file with .pdf
extension and hide the rest. Something like this : <input type="file" id="validatedCustomFile" accept=".pdf" name="document" required>
would work.