ajax file upload
jQuery ajax file upload
jQuery에서 파일 업로드를 하려면 다음과 같은 옵션 설정을 해야한다.
$.ajax({
//...
processData:false,
contentType:false,
//...
});
processData
processData는 data를 쿼리 스트링으로 변환하도록 설정하는 옵션이다.
true - data를 application/x-www-form-urlencoded 형식으로 변환
false - data를 변환 처리하지 않음
contentType
contentType은 요청의 Content-Type
헤더를 정의한다. charset은 항상 UTF-8이다
application/x-www-form-urlencoded
multipart/form-data
text/plain
false
contentType을 multipart/form-data 또는 false로 설정해야 파일 전송이 가능하다.
FormData
FormData는 multipart/form-data 방식에서도 사용할 수 있는 저장소이다. 이를 이용해 파일을 업로드하는 것이 가능하다. 다음과 같이 생성한다.
const formData = new FormData();
전송할 데이터는 다음과 같이 추가한다.
formData.append("key", value);
key는 파라미터 명이며 String 형태로 설정한다. value는 String 또는 Blob으로 설정한다.
File Input에 선택된 파일 확인
File은 input 태그를 이용하여 선택할 수 있다.
<input type="file">
File이 선택되거나 취소되는 경우 change 이벤트가 발생한다.
$("input[type=file]").change(function(){
});
File input에는 files
라는 내장 속성이 존재하며 이를 사용하여 선택된 파일을 확인할 수 있다.
$("input[type=file]").change(function(){
console.log(this.files);
});
선택된 파일이 배열로 관리되기 때문에 파일 선택을 취소한 경우 length가 0이다. 따라서 다음과 같이 조건을 설정할 수 있다.
if(this.files.length > 0){
//파일이 선택된 경우
}
else {
//파일이 선택 해제된 경우
}
파일이 선택된 경우 formData에 이를 담아 비동기로 전송하는 코드는 다음과 같다.
$(".file-selector").change(function(){
if(this.files.length > 0){
const formData = new FormData();
for(let i=0; i < this.files.length; i++){
formData.append("attach", this.files[i]);
}
$.ajax({
url:"서버의업로드주소",
method:"post",
contentType:false,
processData:false,
data:formData,
success:function(resp){
console.log("업로드 성공", resp);
},
error:function(){
console.log("업로드 실패");
}
});
}
});
서버는 구현하지 않았으므로 업로드 주소는 생략하였으며 서버에서 반환하는 응답 정보는 success 함수의 resp에 전달된다. 파일의 개수와 관계없이 첨부된 경우 attach 라는 이름으로 서버에 전달된다.
Last updated