IT News/jQuery

image upload with jQuery and Ajax and return Value is json (ajax 이미지 업로드)

skyLove1982 2017. 11. 9. 11:17
반응형
jQuery 를 이용하여서 title, type, 그리고 이미지 파일을 한개 전송을 한다고 했을때 그것도 aJax를 통해서 말이죠... 적용하느라 하루 이상이 걸렸는데요. 아무튼 여기서 핵심은 FormData  를 생성하고.. 첨부된 파일 정보를 줘야 합니다. 그리고 processData 와 contentType 값을 false 로 해야합니다. 참고로 datatype 를 json 으로 한 이유는 반환받는 값을 json 형태로 값을 인식하기 위함입니다. 이것은 꼭 않하셔도 됩니다.

아래의 예제는 핵심되는 ajax 파일 부분만 있으니 참고만 하시면 될것 같습니다. 

var currentDlg = $('#add_dialog');

var title = currentDlg.find('#title').val();
var type = currentDlg.find('#type').find('option:selected').val();
var coverImage = document.getElementById("coverImage");

var formData = new FormData();
formData.append('title', title);
formData.append('type', type);
formData.append('coverImage', coverImage.files[0]);

$.ajax({
url: "albumAdd.php",
type: 'POST',
data: formData,
dataType: 'json',
enctype: 'multipart/form-data',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (response) {
console.log(response);
if (response.result == "success") {
alert('정상적으로 등록되었습니다.');
location.reload();
} else {
alert(response.data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("일시적인 통신 오류입니다. (code:0001)");
location.reload();
}
});
pointer.removeClass("loading");
currentDlg.find('.cancelBtn').click();


반응형