简体   繁体   English

如何编写文件上传功能ajax,jquery,php? 我应该如何使用Ajax函数编写我的'.submit()'?

[英]How to write file upload function ajax, jquery, php? How should I write my '.submit()' using Ajax function?

 /* -----Progress Bar CSS----- */ #prog-div{ width:100%; max-width: 40%; margin: 0 auto; padding: 50px; display: none; } /* -----Progress Bar----- */ 

 //updated ajax with bootstrap progress bar. <script type="text/javascript"> $(document).ready(function(){ $("#file-submit").click(function(event){ event.preventDefault(); var formdata = new FormData($(this).parents('form')[0]); $.ajax ({ xhr : function(){ $("#prog-div").show(); var xhr =new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(event){ if(event.lengthComputable){ var percent = Math.round((event.loaded / event.total)*100); $('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%'); } }); return xhr; }, type: "POST", url: "upload.php", dataType : 'json', data: formdata, success: function(data){ if(data.status){ alert(data.status); $( "#file-upload" ).val(""); $("#label-text").text("Select Files to Upload"); $("#prog-div").hide(); }else{ $("#prog-div").hide(); alert(data.error); //$("#label-text").text("Select Files to Upload"); } }, processData:false, contentType: false, cache: false }); return false; }) }); </script> 
 <!--my html with bootstrap progressbar below the form--> <!-- Progress Bar --> <div id ="prog-div"> <div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> 0% </div> </div> </div> <!-- Progress Bar --> 

I am trying to build a file upload and need to learn how should I write my '.submit()' using Ajax function will be really helpful. 我正在尝试构建文件上传文件,需要学习如何使用Ajax函数编写我的'.submit()'会很有帮助。 As i am a newbie. 因为我是新手。

As i have read that we have to create formdata object and and intiate the xmlhttp request but i dont understand how to use all this ajax thing together. 正如我所读过的,我们必须创建formdata对象并初始化xmlhttp请求,但我不了解如何一起使用所有这些ajax。 with php for file upload. 与PHP的文件上传。 Please help. 请帮忙。 thanks. 谢谢。

I have tried this ajax code(see below) and i can sense there is something wrong in it. 我已经尝试过此ajax代码(请参见下文),并且我可以感觉到其中存在问题。 Please help me correct it. 请帮我改正。

 <?php header('Content-Type: application/json'); //file upload php code here // //encode the result in json format $json = json_encode(array( 'success' => $success, 'error' => $error )); echo $json; exit(); } ?> 

 <form action="upload.php" method="post" enctype="multipart/form-data" > <input id="file-upload" type="file" name="fileToUpload[]" multiple required> <input type="submit" id="file-submit" value="Upload Selected Files"> </form> 

 //My AJAX Code $(document).ready(function(){ $("#file-submit").click(function(event){ event.preventDefault(); var formdata = new FormData($(this).parents('form')[0]); $.ajax ({ type: "POST", url: "upload.php", data: formdata, success: function(data){ alert("Data uploaded: " +data); }, processData:false, contentType: false, cache: false }); return false; }) }); 

 <?php header('Content-Type: application/json'); //function to get the extension of the file function getExt($name){ $array = explode(".", $name); $ext = strtolower(end($array)); return $ext; } //create global array $allowed = array('jpg', 'png', 'jpeg', 'mp4'); $success = array(); $error = array(); if(isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload'])){ foreach ($_FILES['fileToUpload']['name'] as $key => $name) { $tmp = $_FILES['fileToUpload']['tmp_name'][$key]; $ext = getExt($name); $size = $_FILES['fileToUpload']['size'][$key]; // check the extension is valid or not if(in_array($ext, $allowed) == true){ $filename = md5($name) . time() .'.'.$ext; //check the size of the file if($size <= 10485760){ if(move_uploaded_file($tmp, 'resources/uploaded_files/'.$filename) === true){ $success[] = array('name' => $name, 'location' => 'resources/uploaded_files/'.$filename); }else{ $error[] = array('name' => $name, 'msg' => 'File is not uploaded'); } }else{ $error[] = array('name' => $name, 'msg' => 'File size more than 2MB'); } }else{ $error[] = array('name' => $name, 'msg' => 'File Type not allowed'); } } //encode the result in json format $json = json_encode(array( 'success' => $success, 'error' => $error )); echo $jason; die; exit(); } ?> 

 <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>Files Upload</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!--- Progress Bar Style---> <style> #myBar { width: 10%; height: 30px; background-color: #4CAF50; text-align: center; /* To center it horizontally */ line-height: 30px; /* To center it vertically */ color: white; } </style> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data" > <input id="file-upload" type="file" name="fileToUpload[]" multiple required> <input type="submit" id="file-submit" value="Upload Selected Files" onclick="move()"> </form> <!-- Progress Bar --> <div id="myProgress"> <div id="myBar">0%</div> </div> <script type="text/javascript"> function move() { var elem = document.getElementById("myBar"); var width = 0; var id = setInterval(frame, 0); function frame() { if (width >= 100) { clearInterval(id); } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } $(document).ready(function(){ $("#file-submit").click(function(event){ event.preventDefault(); var formdata = new FormData($(this).parents('form')[0]); $.ajax ({ type: "POST", url: "upload.php", dataType : 'json', data: formdata, success: function(data){ if(data.status){ alert(data.status); }else{ alert(data.error); } }, processData:false, contentType: false, cache: false }); return false; }) }); </script> </body> </html> 

You can try this solution, it support file upload : http://malsup.com/jquery/form/#file-upload 您可以尝试此解决方案,它支持文件上传: http : //malsup.com/jquery/form/#file-upload

    $(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function() { 
            alert("Thank you for your comment!"); 
        }); 
    }); 

Please use the below files code to upload the files and return success or error in the jason format: 请使用以下文件代码上传文件,并以jason格式返回successerror

index.php file code index.php文件代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Files Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data" >
    <input id="file-upload" type="file" name="fileToUpload[]" multiple required>
    <input type="submit" id="file-submit" value="Upload Selected Files">
</form>

<script type="text/javascript">
    $(document).ready(function(){
        $("#file-submit").click(function(event){
        event.preventDefault();
        var formdata = new FormData($(this).parents('form')[0]);

        $.ajax ({
        type: "POST",
        url: "upload.php",
        dataType : 'json',
        data: formdata,
        success: function(data){

            if(data.status){
                alert(data.status);
            }else{
                alert(data.error);
            }
        },
        processData:false,
        contentType: false,
        cache: false
        });
        return false; 
        })
    });
</script>
</body>
</html> 

upload.php file code here 这里的upload.php文件代码

<?php
    function getExt($name){
    $array = explode(".", $name);
    $ext = strtolower(end($array));
    return $ext;
    }

    //create global array
    $allowed = array('jpg', 'png', 'jpeg', 'mp4');
    $message = array();
    $error = array();
    $jason = array();

    if(isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload'])){
      foreach ($_FILES['fileToUpload']['name'] as $key => $name) {
        $tmp = $_FILES['fileToUpload']['tmp_name'][$key];
        $ext = getExt($name);
        $size = $_FILES['fileToUpload']['size'][$key];

        // check the extension is valid or not
        if(in_array($ext, $allowed) == true){
          $filename = md5($name) . time() .'.'.$ext;
        //check the size of the file
        if($size <= 10485760){
          if(move_uploaded_file($tmp, 'uploadFiles/'.$filename) === true){
            $message['status'] = 'File is uploaded successfully';  

          }else{
            $message['error'] = 'File is not uploaded';
          }
        }else{
            $message['error'] = 'File size more than 2MB';
          }
        }else{
          $message['error'] = 'File Type not allowed';
        }
      }

    echo json_encode($message);exit();

    }
?>

Hope this help!! 希望这个帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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