简体   繁体   中英

How to tweak this code for alert box and confirmation box to appear when uploading files

I have an application here where the code for the application is below:

<script type="text/javascript">


var qnum = 1;

function insertQuestion(form) {   


    var $tbody = $('#qandatbl > tbody'); 
    var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
    var $qid = $("<td class='qid'>" + qnum + "</td>");
    var $image = $("<td class='image'></td>");


            var $imagefile = $('<input />')
        .attr({
            type: 'file',
            name: 'imageFile',
            class: 'imageFile'
        });

        $image.append($imagefile);

            var $imageclear = $('<input />')
        .attr({
            type: 'button',
            name: 'imageClear',
            class: 'imageClear',
            value: 'Clear File'
        });

        $image.append($imageclear);


    $tr.append($qid);
    $tr.append($image);   
    $tbody.append($tr); 

}


function validation() {


    var alertValidation = "";
    // Note, this is just so it's declared...


    if (alertValidation != "") {
        alert(_alertValidation);
        return false;
    }

    return true;
}

             function showConfirm(){

         var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Session." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );

         if (confirmMsg==true)
         {
         submitform();   
     }
}

            function submitform()
            {

        var sessionMarksO = document.getElementById("sessionMarks");

          sessionMarksO.submit();

            }


</script>

</head>

<body>

<form id="enter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateForm(this);" >
<div id="detailsBlock">


<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>

</div>
<hr/>

<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
    <th class="qid">Question No</th>
    <th class="image">Image</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

</form> 


<form action="session_marks.php" method="post" id="sessionMarks">

<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="myClickHandler(); return false;" /></p>

</form>

         <script type="text/javascript">

function myClickHandler(){
     if(validation()){
                showConfirm();
     }
}

</script>



</body>
</html>

In the application you click on the "Add Question" button and a new table row is added. Now select a file and click on submit, the confirmation box appears.

Now what I want to do is this below:

I want to include this code below in the application which checks for file formats and file restrictions through server side:

<?php
    if(isset($_POST["submit"])){
        $allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
        $filename = $_FILES['imageFile']['name'];  
        $source = $_FILES['imageFile']['tmp_name'];  
        $file_size=$_FILES['imageFile']['size'];
        $saveloc = "uploads/" . $filename;
        $maxfilesize=1024*1024*10;
        $nameext=explode(".",$filename);
        if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
            if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
                if($file_size<=$maxfilesize){
                    if(!file_exists($saveloc)){
                        if(move_uploaded_file($source, $saveloc)) { 
                            chmod($saveloc,644);
                            echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
                        }
                        else echo "<scirpt type='text/javascript'>alert('Cannot move');</script>";
                    }
                    else echo "<scirpt type='text/javascript'>alert('Existing file');</script>";
                }
                else echo "<scirpt type='text/javascript'>alert('Too big File');</script>";

            }
            else echo "<scirpt type='text/javascript'>alert('Not allowed extension');</script>";
        }
        else echo "<scirpt type='text/javascript'>alert('Only alphanumeric files allowed');</script>";

?>

What I want to know is how can I tweak the code so that if the file is invalid, it displays an alert through the validation() function and if the file is valid, then it should show the confirmation message it is currently showing through the myClickHandler() function?

Thanks

It sounds like you might be blending the server-side and the client-side together in your head. Javascript is a client-side language, which means it runs on your users' machines, in their browser. PHP is a server-side language, which means that it runs on your webserver, and your users see it via the webpages it sends back to your browser.

Now, the problem here is that you want to do, in Javascript, something that can only be done in PHP: validate a file. Javascript can never do this, because browser-makers have put strict limits preventing JS from accessing files on your machine (so that no malicious website can ever steal your personal files). However, you want to prompt your user before the file is uploaded, and it is impossible (without browser plug-ins or something) to do that.

What you can do instead is use an old-school form of AJAX to secretly send the file to your server so that you can validate it, and then look at the response that comes back to decide what to tell the user. I can't write all that code for you, but the basic gist of it is:

  • Put your file input inside a special form, which targets a hidden iframe

For instance:

<iframe id="foo"></iframe>
<form id="bar" target="foo" action="yourServerFile.php">
    <input type="file" id="baz"/>
</form>
  • Add a file (eg. "yourServerFile.php") to your server with the server-side logic you want

  • Add an onReady handler to your hidden IFRAME (eg. $("#foo").ready(function()...); when it triggers, it should look at the html of the IFRAME, and then alert the user (or not) as appropriate based on what it sees there

With all this in place, the basic flow should be:

  1. User clicks on the file input and chooses a file
  2. User clicks the submit button, or hits enter (or alternatively you could add an onBlur handler to the file input to have it trigger the form submission)
  3. The file gets sent to the server (specifically to yourServerFile.php, or whatever you called it)
  4. The server looks at the file, decides whether its valid, and prints out whether its valid or not in the response (this is where the PHP lines from your question come in)
  5. When that response comes back from the server to the hidden iframe, it triggers your onReady handler
  6. Your onReady handler looks at the html of the hidden iframe, and gets whatever validation messages your server wanted to send back (in step #4)
  7. Now that your onReady handler knows whether the file validated or not, it can inform the user appropriately.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM