这是我的PHP代码
for($x=0; $x<count($_FILES['image1']['name']); $x++ ) {
// echo "Hello";
$file_name = $_FILES['image1']['name'][$x];
$file_size = $_FILES['image1']['size'][$x];
$file_tmp = $_FILES['image1']['tmp_name'][$x];
$lclLocation1 = "http://$_SERVER[HTTP_HOST]/images/".$_FILES["image1"]["name"][0];
$lclLocation2 = "http://$_SERVER[HTTP_HOST]/images/".$_FILES["image1"]["name"][1];
$t = explode(".", $file_name);
$t1 = end($t);
$file_ext = strtolower(end($t));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$sumber = $file_tmp;
$tujuan = "../images/" . $file_name;
// echo "Image got";
move_uploaded_file($sumber, $tujuan);
}
else {
echo "Only Images can be store!";
}
} // end for
这是我的ajax查询
// this contains two images
var lclImage1 = document.getElementById("txtImage1");
lclImage2 = lclImage1.files[0];
var formData = new FormData();
formData.append("image1", lclImage2);
此后,我们将ajax发送到PHP。
$.ajax({
url: "user.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
上面的PHP代码可以很好地用于直接使用文件名调用操作,我得到多个值,但是如果我使用ajax,则它不起作用
下面是HTML代码
<form name="imgupload" enctype="multipart/form-data" method="post">
<td rowspan="1">
<input type="file" id="image1" name="image1[]" multiple>
</td>
<input type='submit' name='submit'><br/>
</form>
答案 0 :(得分:0)
您将需要表单提交事件以使ajax如下工作,
for($x=0; $x<count($_FILES['image1']['name']); $x++ ) {
// echo "Hello";
$file_name = $_FILES['image1']['name'][$x];
$file_size = $_FILES['image1']['size'][$x];
$file_tmp = $_FILES['image1']['tmp_name'][$x];
$lclLocation1 = "http://$_SERVER[HTTP_HOST]/images/".$_FILES["image1"]["name"][0];
$lclLocation2 = "http://$_SERVER[HTTP_HOST]/images/".$_FILES["image1"]["name"][1];
if(($_FILES["image1"]["type"][$x] == "image/gif") || ($_FILES["image1"]["type"][$x] == "image/jpeg") || ($_FILES["image1"]["type"][$x] == "image/png") || ($_FILES["image1"]["type"][$x] == "image/pjpeg")){
$sumber = $file_tmp;
$tujuan = "../images/" . $file_name;
// echo "Image got";
move_uploaded_file($sumber, $tujuan);
}
else {
echo "Only Images can be stored!";
}
} // end for
user.php
tidyverse
我还编辑了图像扩展条件。由于文件名的名称中可能带有句点,因此使用句点将文件名爆炸会导致错误。