1. ajax.html (업로드 화면)
<div class="mb-3 mt-3">
<form id="fileForm" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" id="ufile" name="ufile" aria-describedby="fileHelp" multiple>
<div id="fileHelp" class="form-text">We'll never share your FILE with anyone else.</div>
</form>
<button id="ajax_btn" class="btn btn-primary">업로드</button>
<div id="dis"> </div>
</div>
2. Ajax 스크립트
$('#ajax_btn').click(function(){
var formData = new FormData();
var files = $("#ufile")[0].files;
//alert(files.length)
for(var i = 0; i < files.length; i++){
formData.append("fileupload[]", files[i]);
}
$.ajax({
url: './upload.php',
type: 'POST',
dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function (data,status,xhr){
const res = JSON.parse(data);
if (res.result == "success"){
if(res.img.indexOf('|') !=-1){
const imgs = res.img.split('|');
for(let img of imgs){
$('#dis').append('<img src="' + img + '" alt=' + img + '>');
}
}else {
$('#dis').html('<img src="' + res['img'] + '" alt=' +res['img']+ '>');
}
}
},
error: function (flask,html,error){
console.log(flask);
console.log(html);
console.log("에러발생:" + error);
}
});
});
3. upload.php
$cnt = count($_FILES['fileupload']['tmp_name']);
$rs_arr = [];
for($i = 0; $i < $cnt; $i++){
copy($_FILES['fileupload']['tmp_name'][$i], "./upload/" .$_FILES['fileupload']['name'][$i]);
$rs_arr[] = "./upload/".$_FILES['fileupload']['name'][$i];
}
$arr = array("result" => "success", "img" => implode('|',$rs_arr) ); <== JSON 데이터로 배열 보내기가 어려워서 Text로 변환
echo json_encode($arr);
exit;