问题
I want to stop file upload event when i upload the file more than 5mb or if my file extension is not .jpg
or .png
. I found a code but when i try to upload the invalid file type then it only gives me alerts that i have upload the wrong file but it does not cancel the event.
Here is the code
<script>
function checkFile(fieldObj)
{
var FileName = fieldObj.value;
var FileExt = FileName.substr(FileName.lastIndexOf('.')+1);
var FileSize = fieldObj.files[0].size;
var FileSizeMB = (FileSize/5485760).toFixed(2);
if ( (FileExt != "png" && FileExt != "jpg") || FileSize>5485760)
{
var error = "File type : "+ FileExt+"\n\n";
error += "Size: " + FileSizeMB + " MB \n\n";
error += "Please make sure your file is in png or jpg format and less than 5 MB.\n\n";
alert(error);
return false;
}
return true;
}
</script>
and here is html code
<input type="file"onchange="checkFile(this)"name='sec_2_img'>
回答1:
You need to clear the value of 'sec_2_img'. You do this by adding fieldObj.value = "";
after alert(error)
and before return false;
. This will remove the file name from sec_2_img
and force user to select a new one while still showing the message so user knows what to do.
回答2:
1.) Don't use alerts, they are annoying and the browsers will block them pretty fast, so your users won't get any message anymore. Use a modal window or add a styled element with the error-message somewhere into your form.
2.) If you need to have a valid file to submit this form, you have to add a event-handler to the submit-event of the form and stop the trasmission.
3.) your check for file-extension is case-sensitive, this might give you problems on windows, and your calculation of the fileSize is wrong.
来源:https://stackoverflow.com/questions/34654073/how-stop-file-upload-event-using-javascript