note

MultipartFile 인터페이스 사용하여 파일업로드,다운로드(자카르타 라이브러리) 본문

JSP/Spring

MultipartFile 인터페이스 사용하여 파일업로드,다운로드(자카르타 라이브러리)

투한 2012. 3. 6. 11:29


자카르타 라이브러리를 사용합니다































dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">


	<!-- 파일 업로드 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="104857600" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
	<bean class="madvirus.spring.chap06.controller.SubmitReportController" />
	
	
	<!-- View 글로벌 설정 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<!-- 리소스 번들 지정 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	 <property name="basenames">
	 	<list>
	 		<value>messages.validation</value>
	 	</list>
	 </property>
	</bean>
</beans>




madvirus.spring.chap06.model/SubmitReportCommand
package madvirus.spring.chap06.validator;

import madvirus.spring.chap06.model.SubmitReportCommand;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class SubmitReportValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return SubmitReportCommand.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subject", "required");
		SubmitReportCommand command = (SubmitReportCommand) target;
		if(command.getReportFile() == null || command.getReportFile().isEmpty())
			errors.rejectValue("reportFile","required");
	}
}






madvirus.spring.chap06.validator/SubmitReportValidator
package madvirus.spring.chap06.validator;

import madvirus.spring.chap06.model.MemberInfo;
import madvirus.spring.chap06.model.SubmitReportCommand;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class SubmitReportValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return MemberInfo.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subject", "required");
		SubmitReportCommand command = (SubmitReportCommand) target;
		if(command.getReportFile() == null || command.getReportFile().isEmpty())
			errors.rejectValue("reportFile","required");
	}
}


rejectIfEmptyOrWhitespace 메소드 자체가 if문과 같다고 보면됨

required는 리소스 번들로 부터 읽어온다 -> validation.properties 참조 





madvirus.spring.chap06.controller/SubmitReportController
package madvirus.spring.chap06.controller;

import java.io.FileOutputStream;

import madvirus.spring.chap06.model.SubmitReportCommand;
import madvirus.spring.chap06.validator.SubmitReportValidator;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/report/submitReport.do")
public class SubmitReportController {
	// 유효성 체크 클래스 지정
	private Validator validator = new SubmitReportValidator();

	@RequestMapping(method = RequestMethod.GET)
	public String form() {
		return "report/submitReportForm";
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String submit(
			@ModelAttribute("report") SubmitReportCommand command,
			BindingResult errors) throws Exception {
		validator.validate(command, errors);
		if(errors.hasErrors()){
			return form();
		}
		if(!command.getReportFile().isEmpty()){
			String path ="D:/6develop/java/javawork/work_spring/chap06/WebContent/upload";

			byte fileDate[] = command.getReportFile().getBytes();

			FileOutputStream fos = new FileOutputStream(path + "/" + command.getReportFile().getOriginalFilename());

			fos.write(fileDate);
			fos.close();

			System.out.println("주제 : "+command.getSubject());
			System.out.println("업로드한 파일 : "+command.getReportFile().getOriginalFilename());
			System.out.println("소스 코드 크기  :" +command.getReportFile().getSize());

		}
		return "report/submittedReport";
	}
}


GET방식과 POST 방식일때 접근 메소드가 달라짐
유효성 체크에 걸렸을 경우 메세지를 담기 위해BindingResult 사용
hasErrors 에러가 있을 경우 return form()

파일이 있을 경우에 if 문 진입하여서
FileOutputStream 을 형성하여 해당 경로에 데이터를 기술






report/submitReportForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>리포트 등록 폼</title>
</head>
<body>
<spring:hasBindErrors name="report" />
<form action="submitReport.do" method="post" enctype="multipart/form-data">

<p>
	<label for="subject">제목</label>
	<input type="text" id="subject" name="subject" value="${report.subject}">
	<form:errors path="report.subject" />
</p>
<p>
	<label for="reportFile">리포트 파일</label>
	<input type="file" id="reportFile" name="reportFile">
	<form:errors path="report.reportFile" />
</p>
<p>
	<input type="submit" value="리포트 전송">
</p>
</body>
</html>


<spring:hasBindErrors name="report" />
유효성 체크



report/submitedReport.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>리포트 등록 완료</title>
</head>
<body>
리포트 '${report.subject}'를 등록했습니다
</body>
</html> 




다운로드


 


 

인식 실패시 WEB-INF/lib 폴더에 











dispatcherNonHtml-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- 파일 다운로드 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" />
	
	<bean id="downloadController" class="madvirus.spring.chap07.controller.DownloadController" />
	
	<bean id="download" class="madvirus.spring.chap07.view.DownloadView" />
	
	
</beans>

<bean id="download" class="madvirus.spring.chap07.view.DownloadView" />

ModelAndView에 저장된 download를 호출하게 된다

 다운로드를 수행하기 위한등록
<bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" />








DownloadController.java
package madvirus.spring.chap07.controller;

import java.io.File;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

public class DownloadController implements ApplicationContextAware {

	private WebApplicationContext context = null;

	@RequestMapping("/file")
	public ModelAndView download() throws Exception {
		File downloadFile = getFile();
		return new ModelAndView("download", "downloadFile", downloadFile);
	}

	private File getFile() {
		String path = context.getServletContext().getRealPath("/WEB-INF/설명.txt");
		return new File(path);
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.context = (WebApplicationContext)applicationContext;
	}
}



context.getServletContext().getRealPath
전체 경로


ModelAndView에서 download로 저장



 







DownloadView.java
package madvirus.spring.chap07.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownloadView extends AbstractView {

	public DownloadView() {
		setContentType("application/download; charset=utf-8");
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
					throws Exception {
		File file = (File) model.get("downloadFile");

		response.setContentType(getContentType());
		response.setContentLength((int) file.length());

		String userAgent = request.getHeader("User-Agent");
		boolean ie = userAgent.indexOf("MSIE") > -1;
		String fileName = null;
		if (ie) {
			fileName = URLEncoder.encode(file.getName(), "utf-8");
		} else {
			fileName = new String(file.getName().getBytes("utf-8"),
					"iso-8859-1");
		}
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		OutputStream out = response.getOutputStream();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException ex) {
				}
		}
		out.flush();
	}

}








WEB-INF/설명.txt
이건 설명 문서입니다.















'JSP > Spring' 카테고리의 다른 글

Spring 커스텀 태그 / 로그인 유효성 체크  (0) 2012.03.06
Spring 예외처리  (0) 2012.03.06
@PathVariable 을 이용한 주소 확장기능  (0) 2012.03.06
Spring 요청 URI 매칭  (0) 2012.03.05
Spring 유효성 체크  (0) 2012.03.05