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' />";
}
}
}
?>