I am working on PHP form which allows user to upload files to a server directory.
All the following code is in a single file named upload.php
The following code uses a standard HTML Form, which first checks the size of the file the user selects using JAVASCRIPT. If the file size is above limit (1 MB) it is supposed to STOP the upload, show an ALERT message ("File too large. Try uploading smaller size.")
, and then stop processing everything & redirect again to the blank form page upload.php
<form action="" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td><input type="file" name="image" id="imgfile"></td></tr>
<tr><td> <input type="submit" value="upload" name="Submit"></td></tr>
</table>
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('imgfile').files[0];
if(file && file.size < 1000000) { // 1 MB (this size is in bytes)
alert("File within limit. Proceeding with upload.");
} else {
alert("File too large. Try again by uploading smaller size.");
window.location.href ="https://example.com/upload.php";
}
}, false);
</script>
<?php
if(isset($_POST['Submit']))
{
// PHP Server side Code to process submitted file
// Here also I'm checking the file size at server end
}
The code works fine till the ALERT message which is also shown correctly when a large-sized file is selected by the user. However, the problem is that AFTER the alert is shown & user clicks OK, the upload still happens.
I am not very good in JavaScript, so want to know what changes are needed to stop the processing & redirect to happen correctly.
Using https://stackoverflow.com/a/19825478/6337701, I've tried using both window.location & window.location.href, but none are working.