如何使用AJAX将文件类型POST到PHP


How to POST the file type to PHP using AJAX?

我有一个HTML文件,它将图像上传到指定的文件夹和子文件夹。我所面临的问题是,我无法将表单数据POST到PHP。代码如下:

HTML:

    <!DOCTYPE html>
    <html>
    <head>
    <!--<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />-->
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
    <!--<script src="offline.js"></script>-->
    <meta http-equiv="Content-Type" name="viewport" content="width=200, charset=utf-8, initial-scale=1.4, maximum-scale=1.4, minimum-scale=1.4"/>
    <title>JS Bin</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <style>
      article, aside, figure, footer, header, hgroup, 
      menu, nav, section { display: block; }
    </style>
    <script>
    function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#blah')
                        .attr('src', e.target.result)
                        .width(300)
                        .height(340);
                };
                reader.readAsDataURL(input.files[0]);
            }

    }
   </script>
    <script> 
     $("form#form").submit(function(){
                     var formData = new FormData($(this)[0]);
                        $.ajax({
                            url : 'login.php',
                            type: "POST",
                            data : formData,
                            success: function(data, textStatus, jqXHR)
                            {
                                //success 
                            }
                        });
                });
    </script>
    </head>
    <body>
    <form enctype="multipart/form-data" id="form" method="POST">
      <input type="file" required id="image" name="image" onChange="readURL(this);" />
      <img id="blah" src="#" alt="your image" /><br/><br/>
      <button>Submit</button>

        </form>
    </body>
    </html>
PHP

if(isset($_FILES['image']))
    {
  // image upload from html

        session_start();
        $_SESSION['str'];// this is the target where the image is supposed to be stored. 
        $_SESSION['img'];// used to rename the image. 
        $image = basename($_FILES["image"]["name"]);
        echo "$image";  // added to see if the image is being received in the PHP or not.     
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Success";
} 

我要做的是:一旦选项弹出选择一个文件,我有一个函数readURL,显示需要上传的图像的预览。然后,当用户按下SUBMIT按钮时,它应该调用另一个将表单数据POST到PHP的按钮。另一种是不向PHP发送表单数据。请建议怎么做。

添加Js

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script language="javascript" type="text/javascript">
<!-----Add this dev After ----->
<input type="file"  id="image" name="img" />
<div id="dvPreview"></div>

    $(function () {
        $("#image").change(function () {
            $("#dvPreview").html("");
            var regex = /^([a-zA-Z0-9's_''.'-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
            if (regex.test($(this).val().toLowerCase())) {
                if ($.browser.msie && parseFloat(jQuery.browser.version) <= 9.0) {
                    $("#dvPreview").show();
                    $("#dvPreview")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $(this).val();
                }
                else {
                    if (typeof (FileReader) != "undefined") {
                        $("#dvPreview").show();
                        $("#dvPreview").append("<img />");
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            $("#dvPreview img").attr("src", e.target.result);
                        }
                        reader.readAsDataURL($(this)[0].files[0]);
                    } else {
                        alert("This browser does not support FileReader.");
                    }
                }
            } else {
                alert("Please upload a valid image file.");
            }
        });
    });
    </script>
  <script>
  function readURL(input) {
      if(navigator.onLine){ 
        if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(300)
                .height(340);
        };
        reader.readAsDataURL(input.files[0]);
    }
   }else{
      return false;
    }
  }
</script>

100%正常试运行

<form enctype="multipart/form-data" id="form" action="" method="post">
        <input type="file"  id="image" name="img" />
        <img id="blah" src="#" alt="your image" /><br/><br/>
        <input type="button" value="upload" onclick="javascript:uploadInage();" />
    </form>

<script type="text/javascript">
        function uploadInage()
        {
        var file_data = $('#image').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
            $.ajax({
                url: "file.php",
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function (result) {
                        alert(result)
                }
            });
        }
    </script>

file.php

    <?php
    $imagePath = "uploads/";
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    $filename = $_FILES["file"]["tmp_name"];
    $time = time();
    move_uploaded_file($filename, $imagePath . $time . '.' . $extension);    
   echo "File Uploade";
   exit;
 ?>

注意:让文件夹上传

<script>
 function readURL(input) {     
        if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(300)
                .height(340);
        };
        reader.readAsDataURL(input.files[0]);
    }
   uploadfunc();
  }
</script>
<script> 
function uploadfunc(){  
     if(!navigator.onLine){ 
        alert('You are offline');
        return false;   
    }else{
     var formData = new FormData();
     var info_file_data = $('#imageid').prop('files')[0];
     console.log(info_file_data);
      formData.append('info_file', info_file_data);
     $.ajax({
          url: 'login.php', // point to server-side PHP script 
          dataType: 'text',  // what to expect back from the PHP script, if anything
          cache: false,
          contentType: false,
          processData: false,
          data: formData,                         
          type: 'post',
          success: function(php_script_response){
            location.reload();
          }
        });
    }
}
</script>
<!DOCTYPE html>
<html>
<head>
<!--<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />-->
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<!--<script src="offline.js"></script>-->
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Hege Refsnes">
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
<script>
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(300)
                    .height(340);
            };
            reader.readAsDataURL(input.files[0]);
        }
 }
</script>
<script> 
$(document).ready(function (){
        $(".test").click(function(){
             var formData = new FormData();
             var info_file_data = $('#imageid').prop('files')[0];
             console.log(info_file_data);
              formData.append('info_file', info_file_data);
             $.ajax({
                  url: 'login.php', // point to server-side PHP script 
                  dataType: 'text',  // what to expect back from the PHP script, if anything
                  cache: false,
                  contentType: false,
                  processData: false,
                  data: formData,                         
                  type: 'post',
                  success: function(php_script_response){
                   console.log(php_script_response);
                    return;
                  }
                });
        });
  });
</script>
</head>
<body>
  <form enctype="multipart/form-data" id="form" method="POST">
     <input type="file" required id="imageid" name="image" onChange="readURL(this);" />
    <img id="blah" src="#" alt="your image" /><br/><br/>
     <input type="button" class="test" value="submit"/>
  </form>
</body>
</html>

<?php
if(isset($_POST))
{
     if(!empty($_FILES["info_file"]["name"])){
     $target_dir        = "upload/";
     $target_file   = $target_dir .date('Ymdmsh')."_".basename($_FILES["info_file"]["name"]);
     move_uploaded_file($_FILES['info_file']['tmp_name'], $target_file);
 }
 }
  ?>