[현상]

Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request

 

[기존 업로드 구현 방식]

 - multipartResolver를 bean으로 등록 CommonsMultipartResolver를 활용하여 파일 업로드 기능 구현

 - Ajax 호출로 파일 데이터를 전송

 

[문제점]

 - 기존에 사용하던 ajax 공통 호출 함수는 header를 각 호출 장소에서 설정하도록 작성

function callAjax(method, url, data, contentType, fn) {
let xhr = new XMLHttpRequest();
if (!xhr) {
alert('Can not build XMLHttp instance !');
return false;
}
if (method === 'post') {
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.send(data);
} else { /* get, put */
xhr.open(method, url);
xhr.send();
}
xhr.addEventListener('load', fn);
}
view raw ajax_origin hosted with ❤ by GitHub

 - 파일 업로드를 위해 Content-Type에 multipart/form-data를 설정하여 호출했으나 오류발생

 

[해결방식]

 - 기본적인 Ajax 코드로 테스트하여 정상적인 기능 확인

let xhr = new XMLHttpRequest();
xhr.open("post", `/api/reservations/${this.reservationInfoId.value}/comments`, true);
xhr.send(data);
xhr.onload = function(event) {
if(xhr.status == 200) {
console.dir(xhr.status);
debugger;
} else {
console.dir("fail");
}
};
view raw javascript_ajax hosted with ❤ by GitHub

 - setRequestHeader를 제거한 뒤 기존의 ajax 공통 함수 호출 테스트

function callAjax(method, url, data, contentType, fn) {
let xhr = new XMLHttpRequest();
if (!xhr) {
alert('Can not build XMLHttp instance !');
return false;
}
if (method === 'post' && contentType != undefined) {
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.send(data);
} else if(method === 'post') {
/* header 설정 X */
xhr.open(method, url, true);
xhr.send(data);
} else {
/* get, put */
xhr.open(method, url);
xhr.send();
}
xhr.addEventListener('load', fn);
}
view raw ajax hosted with ❤ by GitHub

 

[원인]

 - multipart/form-data로 데이터 전송 시 jquery에서는 contentType을 false로 설정하여 작성되는 글들을 확인

 - 왜 contentType을 multipart/form-data로 설정하면 안되는지 검색

 

[데이터 전송 실패일 때 Request Header]

[데이터 전송 성공일 때 Request Header]

 

 * Content-Type을 확인해보면 boundary의 유무 차이 확인할 수 있다.
 * multipart/form-data를 사용할 때는 Ajax 호출 시 contentType을 설정하지 않아야
정상적으로 multipart/form-data; boundary ...로 파일 이 전송된다.

 

https://repacat.tistory.com/38

 

[파일업로드] Ajax 방식

파일업로드 Ajax 방식의 핵심은 FormData 라는 브라우저에서 지원하는 클래스이다. FormData 는

과 같은 효과를 가져다주는 key/value 가 저장되는 객체이다. 태그처럼 데이터를 처리할 수 있게 해..

 

repacat.tistory.com

 

+ Recent posts