jquery.form 플러그인을 활용한 ajax 파일 업로드 문제 문의합니다.

10,879 views
Skip to first unread message

이랑게

unread,
Mar 1, 2012, 6:47:25 AM3/1/12
to Korea Spring User Group
안녕하세요? 스프링 공부 중인 초보입니다. (꾸벅-)

Jackson을 이용해서 ajax 활용 중인데 get 방식으로는 문제없이 잘 되는데요.
post 방식으로 첨부 파일 업로드 시 문제가 생겨 이렇게 질문을 합니다.

jquery를 사용하고, 첨부 파일 때문에 jquery.form.js 플러그인을 이용해서 파일을 업로드합니다.

먼저 문제를 말씀드리면 FF, 크롬, CoolNovo(크롬 플러스)에서는 원하는 대로 잘 되는데,
IE에서는 json 결과로 넘어오는 객체가 파일로 넘어와서 내려받는 형태로 되어버립니다.
예) {"code":"001","message":"등록되었습니다."} 객체로 넘어와야 할 게 문서로 내려받으라는 형식이 됩니
다. 익스플로러에서만이요.

보시고 원인이나 해결의 실마리를 아시는 분은 조언 좀 해 주시면 고맙겠습니다. (꾸벅-)

<!-- html -->
// 파일 선택 영역, form
<form id="editorFileUpload" action="/upload/${user.id}" method="post"
enctype="multipart/form-data">
<input type="hidden" name="uid" value="${user.uid}" />
<input type="hidden" name="title" value="member" />
<input type="file" name="files" title="첨부파일" />
<input type="submit" value="첨부" />
</form>
// 스크립트
<script type="text/javascript">
$(document).ready(function() {
// jquery.form 플러그인을 이용한 ajax file upload
$("#editorFileUpload").ajaxForm({
success : function(result) {
alert(result.message);
}
});
});
</script>

<!-- controller -->
@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST)
public @ResponseBody Result<File> add(@PathVariable String id,
@ModelAttribute FileManagement fileManagement, Files inputFiles) {

// 폼에서 넘어온 type="file" 파일
List<MultipartFile> files = (List<MultipartFile>)
inputFiles.getFiles();
// 폼에서 넘어온 uid와 title
fileManagement = this.fileManagementService.find(
fileManagement.getUid(), fileManagement.getTitle());

List<File> fileList = null;
// 파일 업로드
if (fileManagement != null) {
fileList = FileUploadUtil.uploadFile(path, fileManagement, files,
id, FileType.EDITOR);
}

return new Result<File>(fileList, "001", "등록되었습니다.");
}

파이어폭스나 크롬에서는 이상 없이 원하는 결과를 얻을 수 있는데,
익스플로러에서는 넘어온 결과가 파일형태로 내려받으라고 합니다.
포털사이트, 구글링 계속해봐도 뾰족한 해법을 못 찾아서 이렇게 글 올립니다.
아시는 분은 조언 좀 해 주세요.


고맙습니다.
수고하시고, 좋은 한 주 보내세요-

Sewon Ann

unread,
Mar 1, 2012, 6:50:42 AM3/1/12
to ks...@googlegroups.com
혹시 json 의 content type 문제는 아닐까요.

현재 content type 이 어떻게 되어있는지 확인하시고, 한번 text/plain 으로 바꿔서 테스트해 보시지요.


--
Google 그룹스 'Korea Spring User Group' 그룹에 가입했으므로 본 메일이 전송되었습니다.
이 그룹에 게시하려면 ks...@googlegroups.com(으)로 이메일을 보내세요.
그룹에서 탈퇴하려면 ksug+uns...@googlegroups.com로 이메일을 보내주세요.
더 많은 옵션을 보려면 http://groups.google.com/group/ksug?hl=ko에서 그룹을 방문하세요.


이상용

unread,
Mar 1, 2012, 7:51:14 PM3/1/12
to ks...@googlegroups.com
도움이 될지는 모르겠지만 저도 jquery.form.js 를 이용하여 비동기식 업로드를 구현하였습니다.

HTML 
<form:form id="frmFile" name="frmFile" modelAttribute="uploadItem"  method="post" enctype="multipart/form-data">
<fieldset>
<legend>파일 첨부</legend>
<p>
<form:label for="fileData" path="fileData"></form:label><form:input id="Filename" path="fileData" type="file"/>
</p>
</fieldset>
</form:form>

Java

public void processAFile(Model model, UploadItem uploadItem,
BindingResult result, HttpServletResponse response) throws Exception {
PrintWriter writer = response.getWriter();
JSONObject returnValue = new JSONObject();
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
CommonUtil.debug(this.getClass(), "Error: " + error.getCode() + " - "
+ error.getDefaultMessage());
}
returnValue.put("result", "error");
writer.print(returnValue.toString());
}
writeProcess(uploadItem); // 업로드 파일에 대한 처리
attachmentService.insertFile(uploadItem); // 업로드된 파일정보를 DB입력
returnValue = uploadItem.toJSON();
returnValue.put("result", "success");
writer.print(returnValue.toString()); // 결과 전달
writer.flush();
writer.close();
}


IE, FF, chorme 다 잘 동작하고있습니다.

참고해보시기바랍니다.



2012년 3월 1일 오후 8:50, Sewon Ann <kin...@gmail.com>님의 말:

Yong-Un Heo

unread,
Mar 1, 2012, 9:16:07 PM3/1/12
to ks...@googlegroups.com
프록시 툴(예:피들러)을 사용해서 해당session의 request 와 response 의 헤더 데이터를 확인해 보시기 바랍니다.



2012년 3월 2일 오전 9:51, 이상용 <kr.goo...@gmail.com>님의 말:

이랑게

unread,
Mar 2, 2012, 7:11:22 PM3/2/12
to Korea Spring User Group
Sewon Ann님 신경 써 주시고, 올려주신 링크 도움이 많이 됐습니다.
고맙습니다.


이상용님 먼저 친절한 샘플 소스 너무나 고맙습니다.
Jackson, @ResponseBody 애노테이션을 활용해서 간단하게 해결하고 싶었는데,
현재 어쩔 수 없이 이 방법으로는 알 될 것 같습니다.
올려주신 소스 활용해서 바꿔야 할 것 같아요.
답변 고맙습니다.


Yong-Un Heo님 말씀해 주신 피들러2 설치해서 확인해 봤습니다.
브라우저별로 비교해 봤는데 특별히 다른 건 못 찾겠더라고요.
답변 고맙습니다.

다 비슷하게 돌아가는데 왜 익스플로러만 마지막에 결과(Result 객체) 값을 문서 형태로 내려받는 식인지 모르겠네요.
혹시 나중에라도 해결하게 되면 자답으로 올리겠습니다.

답변 달아주셔서 너무나 고맙습니다!
모두 좋은 한 주 보내시기 바랄게요- (꾸벅-)

Reply all
Reply to author
Forward
0 new messages