2016-04-29 83 views
3

我要上傳使用$.ajax圖像,但我得到了下面的PHP錯誤:你可以使用Ajax上傳圖片嗎?

undefined index:files

這裏是我的HTML和JS

<form id="image_form" enctype="multipart/form-data"> 
    <input type="file" name="files[]" id="files[]" multiple > 
    <input type="submit" name="submit" is="submit" /> 
</form> 
<div id="result"></div> 
<script src="js/jquery_library.js"></script> 
<script> 
    $(document).ready(function() 
    { 
     $('#image_form').submit(function(e) 
     { 
      e.preventDefault();    
      $.ajax({ 
       method: "POST", 
       url: "upload.php", 
       data: $(this).serialize(), 
       success: function(status) 
       { 
        $('#result').append(status); 
       } 
      }); 
     }); 
    }); 
</script> 

這是我的PHP

<?php 
include 'connect.php'; 
$allowed = array('jpg', 'png', 'jpeg', 'gif', 'bmp'); 
$myFile = $_FILES['files']; 
$fileCount = count($myFile["name"]); 

for ($i = 0; $i < $fileCount; $i++) 
{ 
    $name = $myFile["name"][$i]; 
    $type = $myFile['type'][$i]; 
    $tmp_name = $myFile['tmp_name'][$i]; 
    $result = substr(sha1(mt_rand()),0,50); 
    $explode = explode(".",$myFile["name"][$i]); 
    $ext = end($explode); 
    $target = "photos/".$result.".".$ext; 

    if(in_array($ext, $allowed)) 
    { 
     if(move_uploaded_file($tmp_name,$target)) 
     { 
      mysqli_query($con, "INSERT INTO images VALUES('".$target."')"); 
      echo "<img src='$target' />"; 
     } 
    } 
} 
?> 

回答

1

我已經想通了,這是它:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 

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

//upload.php 

<?php 

include 'connect.php'; 

if(is_array($_FILES)) 
{ 
     foreach ($_FILES['files']['name'] as $name => $value) 
     { 
      $file_name = explode(".", $_FILES['files']['name'][$name]); 
      $allowed_ext = array("jpg", "jpeg", "png", "gif"); 
      if(in_array($file_name[1], $allowed_ext)) 
      { 
       $new_name = substr(sha1(mt_rand()),0,50) . '.' . $file_name[1]; 
       $sourcePath = $_FILES['files']['tmp_name'][$name]; 
       $target = "photos/".$new_name; 
       if(move_uploaded_file($sourcePath, $target)) 
       { 
        mysqli_query($con, "INSERT INTO images VALUES('".$target."')"); 
        echo "<img src='$target' />"; 
       }     
      }    
     } 
} 

?>