使用ajax或javascript进行php进程上传

时间:2015-09-12 16:59:39

标签: javascript php jquery ajax

我有表格和上传图片,工作正常我想通过ajax或javascript处理它。如何使用javascript调整我的代码,这样它就不会刷新页面,只会打印一条消息UPLOADED Successfully。任何帮助将受到高度赞赏。 我的代码如下:

HTML:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>

</body>
</html>

我的JS:

<script type="text/javascript">
$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
        e.preventDefault();
        $.ajax({
            url: "upload.php",
            type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            error: function() 
            {
            }           
       });
    }));
});
</script>

upload.php的:

<?php

function uploadFile ($file_field = null, $check_image = false, $random_name = false) {

  //Config Section    
  //Set file upload path
  $path = 'uploads/'; //with trailing slash
  //Set max file size in bytes
  $max_size = 1000000;
  //Set default file extension whitelist
  $whitelist_ext = array('jpg','png','gif');
  //Set default file type whitelist
  $whitelist_type = array('image/jpeg', 'image/png','image/gif');

  //The Validation
  // Create an array to hold any output
  $out = array('error'=>null);

  if (!$file_field) {
    $out['error'][] = "Please specify a valid form field name";           
  }

  if (!$path) {
    $out['error'][] = "Please specify a valid upload path";               
  }

  if (count($out['error'])>0) {
    return $out;
  }

  //Make sure that there is a file
  if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {

    // Get filename
    $file_info = pathinfo($_FILES[$file_field]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension           
    if (!in_array($ext, $whitelist_ext)) {
      $out['error'][] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
      $out['error'][] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$file_field]["size"] > $max_size) {
      $out['error'][] = "File is too big";
    }

    //If $check image is set as true
    if ($check_image) {
      if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
        $out['error'][] = "Uploaded file is not a valid image";
      }
    }

    //Create full filename including path
    if ($random_name) {
      // Generate random filename
      $tmp = str_replace(array('.',' '), array('',''), microtime());

      if (!$tmp || $tmp == '') {
        $out['error'][] = "File must have a name";
      }     
      $newname = $tmp.'.'.$ext;                                
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
      $out['error'][] = "A file with this name already exists";
    }

    if (count($out['error'])>0) {
      //The file has not correctly validated
      return $out;
    } 

    if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
      //Success
      $out['filepath'] = $path;
      $out['filename'] = $newname;
      return $out;
    } else {
      $out['error'][] = "Server Error!";
    }

  } else {
    $out['error'][] = "No file uploaded";
    return $out;
  }      
}
?>
<?php
if (isset($_POST['submit'])) {
  $file = uploadFile('file', true, true);
  if (is_array($file['error'])) {
    $message = '';
    foreach ($file['error'] as $msg) {
      $message .= '<p>'.$msg.'</p>';    
    }
  } else {
    $message = "File uploaded successfully";
  }
  echo $message;
}
?>

3 个答案:

答案 0 :(得分:1)

我有表格和上传图片,工作正常我想通过ajax或javascript处理它。如何使用javascript调整我的代码,这样它就不会刷新页面,只会打印一条消息UPLOADED Successfully。 我为我的问题尝试了很多,而且我成功了。答案如下:

<强> HTML

<script src="js/jquery.min.js"></script>
<script src="js/ajax-upload.js"></script>

<form id="frmUpload" action="" method="POST" name="default" class="form-horizontal">
<div class="img-upload">
<input type="file" name="file" id="file" class="user-image" required />
<div class="img-preview"></div>
<div class="upload-msg"></div>
</div>
    <div class="form-actions">
        <input type="submit" name="submit" value="Add Image Or Audio File" class="btn btn-primary">   
        <input type="reset" name="reset" value="Reset" class="btn">
    </div>
</form>

<强> Ajax的upload.js

$(document).ready(function (e) {

    $("#frmUpload").on('submit',(function(e) {
        e.preventDefault();
        $(".upload-msg").text('Loading...');    
        $.ajax({
            url: "process.php",        // Url to which the request is send
            type: "POST",             // Type of request to be send, called as method
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function(data)   // A function to be called if request succeeds
            {
                $(".upload-msg").html(data);
            }
        });
    }


));

// Function to preview image after validation

$("#file").change(function() {
    $(".upload-msg").empty(); 
    var file = this.files[0];
    var imagefile = file.type;
    var imageTypes= ["image/jpeg","image/png","image/jpg","image/gif"];
        if(imageTypes.indexOf(imagefile) == -1)
        {
            $(".upload-msg").html("<span class='msg-error'>Please Select A valid Image File</span><br /><span>Only jpeg, jpg and png Images type allowed</span>");
            return false;
        }
        else
        {
            var reader = new FileReader();
            reader.onload = function(e){
                $(".img-preview").html('<img src="' + e.target.result + '" />');                
            };
            reader.readAsDataURL(this.files[0]);
        }
    }); 
});

<强> process.php

<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {

  //Config Section    
  //Set file upload path
  $path = 'uploads/'; //with trailing slash
  //Set max file size in bytes
  $max_size = 1000000;
  //Set default file extension whitelist
  $whitelist_ext = array('jpg','png','gif');
  //Set default file type whitelist
  $whitelist_type = array('image/jpeg', 'image/png','image/gif');

  //The Validation
  // Create an array to hold any output
  $out = array('error'=>null);

  if (!$file_field) {
    $out['error'][] = "Please specify a valid form field name";           
  }

  if (!$path) {
    $out['error'][] = "Please specify a valid upload path";               
  }

  if (count($out['error'])>0) {
    return $out;
  }

  //Make sure that there is a file
  if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {

    // Get filename
    $file_info = pathinfo($_FILES[$file_field]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension           
    if (!in_array($ext, $whitelist_ext)) {
      $out['error'][] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
      $out['error'][] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$file_field]["size"] > $max_size) {
      $out['error'][] = "File is too big";
    }

    //If $check image is set as true
    if ($check_image) {
      if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
        $out['error'][] = "Uploaded file is not a valid image";
      }
    }

    //Create full filename including path
    if ($random_name) {
      // Generate random filename
      $tmp = str_replace(array('.',' '), array('',''), microtime());

      if (!$tmp || $tmp == '') {
        $out['error'][] = "File must have a name";
      }     
      $newname = $tmp.'.'.$ext;                                
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
      $out['error'][] = "A file with this name already exists";
    }

    if (count($out['error'])>0) {
      //The file has not correctly validated
      return $out;
    } 

    if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
      //Success
      $out['filepath'] = $path;
      $out['filename'] = $newname;
      return $out;
    } else {
      $out['error'][] = "Server Error!";
    }

  } else {
    $out['error'][] = "No file uploaded";
    return $out;
  }      
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_FILES["file"]["type"])){
  $file = uploadFile('file', true, true);
  if (is_array($file['error'])) {
    $message = '';
    foreach ($file['error'] as $msg) {
      $message .= '<p>'.$msg.'</p>';    
    }
  } else {

    $message = "File uploaded successfully";
  }
  echo $message;
}
?>

答案 1 :(得分:-1)

使用success的{​​{1}}属性作为函数,在成功请求后执行一些代码。

例如:

$.ajax

答案 2 :(得分:-1)

假设您从php获得了正确的响应,那么这应该是好的,

太懒了解释,哈哈

HTML

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <style>
        body {
            position: relative;
        }
        .loader {
            position: absolute;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.42);
            display: none;
        }
        .loader.active {
            display: block;
        }
    </style>
</head>
<body>

    <div class="loader"></div>
    <form id="uploadForm" method="post" enctype="multipart/form-data">
    <input name="file" type="file" size="20" />
    <input name="submit" type="submit" value="Upload" />
    </form>
    <div class="notice"></div>

</body>
</html>

<强> EDITED

首先确保控制台日志没有错误, 然后检查控制台日志中的所有内容

<script type="text/javascript">
    $(document).ready(function () {

        // Capture Form Submit Aaction
        $("#uploadForm").on('submit',(function() {

            // Show Loader Div when Button is click
            $('.loader').addClass('active');

            // Add Console Message confirming button is click
            console.log('Start Ajax');

            // Start Ajax Request
            $.ajax({
                type: 'POST',

                // Place URL upload.php url here
                url: 'http://yoursite.com/filesordir/upload.php',

                // Never check your PHP data so I leave this lines below,
                data:  new FormData(this),
                contentType: false,
                cache: false,
                processData:false,

                // If ajax response is success
                success: function(data) { 

                    // Hide the Loader Div
                    $('.loader').removeClass('active');

                    // Inser Ajax response to notice div
                    $('.notice').html( data );

                    // Add Console message
                    console.log('Ajax Success');
                }
                error: function( errorThrown ) {

                    // Hide the Loader Div
                    $('.loader').removeClass('active');

                    // Inser error message to notice div
                    $('.notice').html( errorThrown );

                    // Add Console message
                    console.log('Ajax Error');
                }           
           });

        //Edited this, have double ")".
        });
    });
    </script>