php,ajax上传文件,多文件上传

时间:2021-11-24 07:39:58

HTML

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="src/jquery1.11.1.js"></script>
</head>
<body>
<form id= "uploadForm" action= "" method= "post" enctype ="multipart/form-data">
<h1 >多文件上传 </h1>
<table>
<tr>
<td >上传文件: <input type ="file" name="myfile[]" id="file" multiple="multiple"/><a href="javascript:;" id="add">[+]</a></td>
</tr>
<tr>
<td>
<input type ="button" value="上传" id="but"/>
</td>
</tr>
</table>
</form>
</body>
</html>
<script>
//添加
$(document).on("click","#add",function(){
var str_tr = "<tr>"+$(this).parents("tr").html()+"</tr>";
//js 替换字符串样式
str_tr = str_tr.replace(/\+/,'-');
var new_str_tr = str_tr.replace(/add/,'del');
$(this).parents("tr").after(new_str_tr);
})
//删除
$(document).on("click","#del",function(){
$(this).parents("tr").remove();
}) //文件上传
$("#but").click(function(){
var formData = new FormData($( "#uploadForm" )[0]);
$.ajax({
url: 'up.php' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
})
</script>

PHP

<?php
header('Access-Control-Allow-Origin:*');
$fileArray = $_FILES['myfile'];
if($fileArray){
$upload_dir ="upload_path/";
if($fileArray){
foreach ($fileArray['error'] as $key => $error) {
if ( $error == UPLOAD_ERR_OK ) { //PHP常量UPLOAD_ERR_OK=0,表示上传没有出错
$tmp_name = $fileArray['tmp_name'][$key];
$file_name = $fileArray['name'][$key];
$file_name = iconv("UTF-8","gbk",$file_name);
move_uploaded_file($tmp_name, $upload_dir.$file_name);
echo "上传成功\n";
}else{
$key = $key + 1;
echo "第".$key."个文件上传出错\n";
}
}
}else{
echo "nonono";
}
}