이미 있는 html에서의 ajax 업로드는 아래 링크로 가면 나와 있다.
링크
http://b1ix.net/213
그런데, 동적으로 생성된 엘리먼트의 경우 위의 링크처럼 해도 FormData에서 해당 엘리먼트들을 인식하지 못한다.
이럴 경우에는 임의의 FormData객체를 만든 뒤에 해당 객체에 직접 엘리먼트의 값들을 넣어주면 된다.
일단 예제를 보자
<div id="div1"></div>
<button type="button" id="btn1">submit</button>
<script type="text/javascript">
$(function(){
// 동적으로 엘리먼트 추가
var tmp1 = "<input type='text' id='input1' value='b1ix.net'>"
tmp1 += "<input id='file1' type='file'>"
$('#div1').append(tmp1)
$('#btn1').click(function(){
// 임의의 FormData객체 생성
var tmp_form = new FormData()
// 동적 text 타입 엘리먼트 추가
tmp_form.append('input1', $('#input1').val())
// 동적 file 타입 엘리먼트 추가
tmp_form.append('file1', $('#file1')[0].files[0]);
$.ajax({
type: 'post'
,url: '/410'
,processData: false
,contentType: false
,data: tmp_form
,success: function(data){
// console.log(data)
}
,error: function(xhr, status, msg){
console.log(xhr)
}
});
})
})
</script>
위와 같이 div에 동적으로 text타입과 file타입의 엘리먼트를 추가하고, 임의의 FormData객체를 만들어서 input타입 엘리먼트를 추가해 준다.
여기서 file타입인 경우에는 위의 예제처럼 추가해야 서버에 file로 인식해서 올라간다.
아래는 서버에서 위의 데이터가 잘 전송되는지 확인 해본 결과이다.
<?php
echo '$_POST<br>';
print_r($_POST);
echo '$_FILES<br>';
print_r($_FILES);
?>
$_POST
Array
(
[input1] => b1ix.net
)
$_FILES
Array
(
[file1] => Array
(
[name] => gle.png
[type] => image/png
[tmp_name] => /tmp/phpsR7b3D
[error] => 0
[size] => 5183
)
)
input타입은 POST로 file타입은 FIELS로 잘 넘어와 있다.