티스토리 뷰


   예전에 cos.jar를 이용한 파일업로드 방법을 포스팅한 적이 있는데(http://zero-gravity.tistory.com/168), 이번엔 스프링에서 제공하는 CommonsMultipartResolver를 이용한 파일업로드 방법을 소개하겠다. cos.jar는 상용으로 사용하려면 라이선스를 구입해야 한댄다. 물론 몰래 사용해도 걸릴 확률은 극히 없지만, 양심상..ㅡ.ㅡ;;




   * Spring bean 설정 파일에 CommonsMultipartResolver 빈 등록


	


   property는 이클립스 코드어시스트로 받아보면 대략 알 수 있을 것이다. 필자는 파일 용량 제한하는 것만 사용했음.




   * JSP




   * Controller

@RequestMapping("/uploadFile.do")
public String uploadFile(HttpServletRequest request, @RequestParam("imgFile") MultipartFile imgFile
				, Model model){
	// String savePath = "D:/Projects/workspace/projectName/WebContent/folderName";
	String savePath = request.getRealPath("folderName"); // 파일이 저장될 프로젝트 안의 폴더 경로
	
	String originalFilename = imgFile.getOriginalFilename(); // fileName.jpg
	String onlyFileName = originalFilename.substring(0, originalFilename.indexOf(".")); // fileName
	String extension = originalFilename.substring(originalFilename.indexOf(".")); // .jpg
	
	String rename = onlyFileName + "_" + getCurrentDayTime() + extension; // fileName_20150721-14-07-50.jpg
	String fullPath = savePath + "\\" + rename;
	
	if (!imgFile.isEmpty()) {
		try {
			byte[] bytes = imgFile.getBytes();
			BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fullPath)));
			stream.write(bytes);
			stream.close();
			model.addAttribute("resultMsg", "파일을 업로드 성공!");
		} catch (Exception e) {
			model.addAttribute("resultMsg", "파일을 업로드하는 데에 실패했습니다.");
		}
	} else {
		model.addAttribute("resultMsg", "업로드할 파일을 선택해주시기 바랍니다.");
	}
	
	return "jspPage";
}

public String getCurrentDayTime(){
	long time = System.currentTimeMillis();
	SimpleDateFormat dayTime = new SimpleDateFormat("yyyyMMdd-HH-mm-ss", Locale.KOREA);
	return dayTime.format(new Date(time)); 
}




   위와 같이 savePath로 매번 파일을 업로드할 경로를 지정할 수도 있지만, CommonsMultipartResolver를 빈등록할 때, 프로퍼티로 지정해줄 수도 있다.


   FileSystemResource 빈 등록을 해주고,

<bean id="fileSystemResource" class="org.springframework.core.io.FileSystemResource">

<constructor-arg>

<value>파일을 업로드할 경로</value>

</constructor-arg>

</bean>


   CommonsMultipartResolver 빈등록한 부분에서 uploadTempDir property를 추가한 다음 ref를 FileSystemResource 빈등록했던 id로 걸어주면 된다.

<property name="uploadTempDir" ref="fileSystemResource"></property>




댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
31
글 보관함