Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 국제화
- AWT
- 예외처리
- 이클립스
- 어노테이션
- 전화걸기
- Android
- Graphic
- 에러페이지
- 배열
- Java
- Spring
- 오버로딩
- 메소드
- layout
- JSP
- paint
- 안드로이드
- Eclips
- JavaScript
- 메서드
- 클래스
- OGNL
- HTML
- mybatis
- struts2
- oracle
- Menu
- 생성자
- 기본
Archives
- Today
- Total
note
MultipartFile 인터페이스 사용하여 파일업로드,다운로드(자카르타 라이브러리) 본문
자카르타 라이브러리를 사용합니다
파일 업로드에 관한 글
[JSP/스트럿츠2] - struts2 업로드파일 다운로드 하기
[JSP/스트럿츠2] - struts2 파일 업로드(자카르타 라이브러리)
[JSP/기본] - JSP 파일 업로드 (Servlets.com) cos라이브러리 사용
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" %>
리포트 등록 폼
유효성 체크report/submitedReport.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
리포트 등록 완료
리포트 '${report.subject}'를 등록했습니다
다운로드
인식 실패시 WEB-INF/lib 폴더에
dispatcherNonHtml-servlet.xml
ModelAndView에 저장된 download를 호출하게 된다
다운로드를 수행하기 위한등록
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 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 |