티스토리 뷰

Programming/Java

Spring 파일 업로드

파란크리스마스 2012. 7. 31. 15:44
728x90

Spring Controller

@Controller
@RequestMapping(value = "/form/mfile_add")
public class CMXFileAddController {

	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		MFile mFile = new MFile ();
		model.addAttribute("mFile", mFile);
		return "/form/mfile_add";
	}

mfile_add.jsp

<form:form modelAttribute="mFile" method="post" enctype="multipart/form-data">

        <legend>자료 등록</legend>

        <table>
          <TR>
            <TD><form:label for="title" path="title">제목</form:label></TD>
            <TD><form:input path="title" type="text" size="85"/></TD>
          </TR>
          <TR>
            <TD><form:label for="file1" path="file1">파일1</form:label></TD>
            <TD><form:input path="file1" type="file" size="70"/></TD>
          </TR>
          <TR>
            <TD><form:label for="desc" path="desc">설명</form:label></TD>
            <TD><form:textarea path="desc" cols="84" rows="5" /></TD>
          </TR>
        </table>

        <input type="submit" value="등록"/>

</form:form>

Post 파일 업로드 처리

	@RequestMapping(method = RequestMethod.POST)
	public String create(MFile mFile, BindingResult result) {
		
		System.out.println(mFile);
		
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
			}
			return "/form/mfile_add";
		}

		if (!mFile.getFile1().isEmpty()) {
			String filename = mFile.getFile1().getOriginalFilename();
			String imgExt = filename.substring(filename.lastIndexOf(".") + 1, filename.length());

			// upload 가능한 파일 타입 지정
			if (imgExt.equalsIgnoreCase("xls")) {
				byte[] bytes = mFile.getFile1().getBytes();
				try {
					File lOutFile = new File(fsResource.getPath() + filename  + "_temp.xls");
					FileOutputStream lFileOutputStream = new FileOutputStream(lOutFile);
					lFileOutputStream.write(bytes);
					lFileOutputStream.close();
				} catch (IOException ie) {
					// Exception 처리
					System.err.println("File writing error! ");
				}
				System.err.println("File upload success! ");
			} else {
				System.err.println("File type error! ");
			}
		
		}
		return "redirect:mfile_list.itg";
	}

 

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함