简体   繁体   中英

How to POST the file type to PHP using AJAX?

I have an HTML file that uploads an image to the designated folders and subfolders. The problem that I'm facing is that I'm unable to POST the form data to the PHP. Below is the code.

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";
} 

What I'm trying to do is: once the option pops up to choose a file I have a function readURL that shows the preview of the image that needs to be uploaded. Then when the user presses the SUBMIT button it should call another that POST the form data to PHP. But the other is not sending the form data to the PHP. Kindly suggest what to do.

  <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% Working Try This.

<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;
 ?>

NOte :make folder uploads

<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);
 }
 }
  ?>

Add this 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>

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