package springmvc.fileup.ctr;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import springmvc.fileup.dto.MultiupDTO;
import springmvc.fileup.dto.SingleUpDTO;
@Controller
public class FileUploadController {
private String uploadDirectory;//upload된 파일을 저장할 디렉토리
public FileUploadController(String uploadDirectory) {//최종 저장소가 안바뀐다는 가정하에 생성자에서 주입 받음
super();
this.uploadDirectory = uploadDirectory;
}
//파일을 받는 변수 앞에는 @RequestParam을 붙여준다.
@RequestMapping("/singleUp.do")
public ModelAndView singleUp(String comment,@RequestParam MultipartFile upfile)throws Exception{
boolean b = upfile.isEmpty();//false이면 업도드된 파일이 있다.
HashMap map = new HashMap();
if(upfile!=null && !b){
System.out.println("-----------업로드된 파일 정보------------");
String fileName = upfile.getOriginalFilename();
long fileSize = upfile.getSize();
System.out.println("파일명 : "+fileName+", 크기 : "+fileSize);
//파일 이동(임시저장소 upfile의 정보를 영구적 저장소 uploadDirectory로 보내준다)
upfile.transferTo(new File(uploadDirectory,fileName));
map.put("fileName", fileName);
}
System.out.println("코멘트 : "+comment);
map.put("comment", comment);
return new ModelAndView("single_res", map);
}
@RequestMapping("/singleUpDTO.do")
public ModelAndView singleUpDTO(SingleUpDTO sto)throws Exception{
MultipartFile upfile = sto.getUpfile();
String comment = sto.getComment();
if(!upfile.isEmpty()){
System.out.println("파일명 : "+upfile.getOriginalFilename());
System.out.println("파일크기 : "+upfile.getSize());
//파일이동
upfile.transferTo(new File(uploadDirectory,upfile.getOriginalFilename()));
}
System.out.println("comment : "+comment);
return new ModelAndView("single_res","sto",sto);
}
@RequestMapping("/singleUpReq.do")
public ModelAndView singleUpReq(MultipartHttpServletRequest request)throws Exception{
System.out.println("---------getFileNames() : 요청파라미터의 이름들 리턴 - type이 file인---------");
Iterator<String> itr = request.getFileNames();
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("---------getParameter(), getParameterValues()");
System.out.println("코멘트 : "+request.getParameter("comment"));
System.out.println("--------getFile() : 업로드 파일정보 조회");
MultipartFile upfile = request.getFile("upfile");
if(!upfile.isEmpty()){
System.out.println("파일명 : "+upfile.getOriginalFilename());
upfile.transferTo(new File(uploadDirectory, upfile.getOriginalFilename()));
}
System.out.println("------getFiles() : 동일한 이름으로 여러개의 파일 업로드 시");
List<MultipartFile> list = request.getFiles("myupfile");
for(MultipartFile file : list){
if(!file.isEmpty()){
String fileName = file.getOriginalFilename();
System.out.println("myfile : "+fileName);
//이동
file.transferTo(new File(uploadDirectory,fileName));
}
}
SingleUpDTO sto = new SingleUpDTO();
sto.setComment(request.getParameter("comment"));
sto.setUpfile(upfile);
HashMap map = new HashMap();
map.put("sto", sto);
map.put("list", list);
return new ModelAndView("single_res",map);
}
@RequestMapping("/multiUp.do")
public ModelAndView multiUp(MultiupDTO mto) throws Exception{
String comment = mto.getComment();
List<MultipartFile> list = mto.getUpfile();
for(MultipartFile file : list){
if(!file.isEmpty()){
String fileName = file.getOriginalFilename();
long size = file.getSize();
System.out.println(fileName+" - "+size);
//파일 이동(파일 카피가 아님)
file.transferTo(new File(uploadDirectory,fileName));
}
}
System.out.println("comment : "+comment);
return new ModelAndView("multi_res","mto",mto);
}
}
package springmvc.fileup.dto;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultiupDTO {
private String comment;
private List<MultipartFile> upfile;
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List<MultipartFile> getUpfile() {
return upfile;
}
public void setUpfile(List<MultipartFile> upfile) {
this.upfile = upfile;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
Comment : ${requestScope.mto.comment }<br>
업로드된 파일들<br>
<c:forEach items="${requestScope.mto.upfile }" var="file">
${file.originalFilename }<br>
</c:forEach>
</body>
</html>
<?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">
<!-- ViewResolver -->
<bean name="vr" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/res/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- multipartResolver -->
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- <property name="maxUploadSize" value="1048576"/> --><!--1M : 1024*1024, 1048576 -->
</bean>
<!-- Controller -->
<bean name="fileUploadController" class="springmvc.fileup.ctr.FileUploadController">
<constructor-arg value="D:\apache-tomcat-6.0.35\webapps\SpringMVC_04_fileUpload\upload"/>
</bean>
</beans>
<!-- /application Root/upload -->
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- DispatcherServlet 등록(front controller) -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 한글 encoding 처리 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<%@ 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>Insert title here</title>
</head>
<body>
<form action="multiUp.do" method="post" enctype="multipart/form-data">
Comment : <input type="text" name="comment"><br>
파일<br>
<input type="file" name="upfile[0]"><br>
<input type="file" name="upfile[1]"><br>
<input type="file" name="upfile[2]"><br>
<input type="submit" value="전송"><br>
</form>
</body>
</html>
* 결과
Chrysanthemum.jpg - 879394Lighthouse.jpg - 561276
Desert.jpg - 845941
comment : 123
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
Comment : ${requestScope.mto.comment }<br>
업로드된 파일들<br>
<c:forEach items="${requestScope.mto.upfile }" var="file">
<a href="/SpringMVC_04_fileUpload/upload/${file.originalFilename }">
${file.originalFilename }
</a><br>
</c:forEach>
</body>
</html>
* 결과
* txt나 그림파일 html파일은 브라우저가 실행할 수 있다고 생각해서 다운 받지 않고 바로 실행시킨다. 그래서 아래서 다시 브라우저가 알 수 없는 파일로 지정하여 다운로드 할 수 있게 할 것이다.
* 실습
package springmvc.fileup.ctr;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import springmvc.fileup.dto.MultiupDTO;
import springmvc.fileup.dto.SingleUpDTO;
@Controller
public class FileUploadController {
private String uploadDirectory;//upload된 파일을 저장할 디렉토리
public FileUploadController(String uploadDirectory) {//최종 저장소가 안바뀐다는 가정하에 생성자에서 주입 받음
super();
this.uploadDirectory = uploadDirectory;
}
//파일을 받는 변수 앞에는 @RequestParam을 붙여준다.
@RequestMapping("/singleUp.do")
public ModelAndView singleUp(String comment,@RequestParam MultipartFile upfile)throws Exception{
boolean b = upfile.isEmpty();//false이면 업도드된 파일이 있다.
HashMap map = new HashMap();
if(upfile!=null && !b){
System.out.println("-----------업로드된 파일 정보------------");
String fileName = upfile.getOriginalFilename();
long fileSize = upfile.getSize();
System.out.println("파일명 : "+fileName+", 크기 : "+fileSize);
//파일 이동(임시저장소 upfile의 정보를 영구적 저장소 uploadDirectory로 보내준다)
upfile.transferTo(new File(uploadDirectory,fileName));
map.put("fileName", fileName);
}
System.out.println("코멘트 : "+comment);
map.put("comment", comment);
return new ModelAndView("single_res", map);
}
@RequestMapping("/singleUpDTO.do")
public ModelAndView singleUpDTO(SingleUpDTO sto)throws Exception{
MultipartFile upfile = sto.getUpfile();
String comment = sto.getComment();
if(!upfile.isEmpty()){
System.out.println("파일명 : "+upfile.getOriginalFilename());
System.out.println("파일크기 : "+upfile.getSize());
//파일이동
upfile.transferTo(new File(uploadDirectory,upfile.getOriginalFilename()));
}
System.out.println("comment : "+comment);
return new ModelAndView("single_res","sto",sto);
}
@RequestMapping("/singleUpReq.do")
public ModelAndView singleUpReq(MultipartHttpServletRequest request)throws Exception{
System.out.println("---------getFileNames() : 요청파라미터의 이름들 리턴 - type이 file인---------");
Iterator<String> itr = request.getFileNames();
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("---------getParameter(), getParameterValues()");
System.out.println("코멘트 : "+request.getParameter("comment"));
System.out.println("--------getFile() : 업로드 파일정보 조회");
MultipartFile upfile = request.getFile("upfile");
if(!upfile.isEmpty()){
System.out.println("파일명 : "+upfile.getOriginalFilename());
upfile.transferTo(new File(uploadDirectory, upfile.getOriginalFilename()));
}
System.out.println("------getFiles() : 동일한 이름으로 여러개의 파일 업로드 시");
List<MultipartFile> list = request.getFiles("myupfile");
for(MultipartFile file : list){
if(!file.isEmpty()){
String fileName = file.getOriginalFilename();
System.out.println("myfile : "+fileName);
//이동
file.transferTo(new File(uploadDirectory,fileName));
}
}
SingleUpDTO sto = new SingleUpDTO();
sto.setComment(request.getParameter("comment"));
sto.setUpfile(upfile);
HashMap map = new HashMap();
map.put("sto", sto);
map.put("list", list);
return new ModelAndView("single_res",map);
}
@RequestMapping("/multiUp.do")
public ModelAndView multiUp(MultiupDTO mto) throws Exception{
String comment = mto.getComment();
List<MultipartFile> list = mto.getUpfile();
for(MultipartFile file : list){
if(!file.isEmpty()){
String fileName = file.getOriginalFilename();
long size = file.getSize();
System.out.println(fileName+" - "+size);
//파일 이동(파일 카피가 아님)
file.transferTo(new File(uploadDirectory,fileName));
}
}
System.out.println("comment : "+comment);
return new ModelAndView("multi_res","mto",mto);
}
//다운 로드 처리
@RequestMapping("/download.do")
public ModelAndView download(String fileName) throws Exception{
return new ModelAndView("downloadView", "fileName", fileName);
}
}
package springmvc.fileup.dto;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultiupDTO {
private String comment;
private List<MultipartFile> upfile;
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List<MultipartFile> getUpfile() {
return upfile;
}
public void setUpfile(List<MultipartFile> upfile) {
this.upfile = upfile;
}
}
package springmvc.fileup.dto;
import org.springframework.web.multipart.MultipartFile;
public class SingleUpDTO {
private String comment;
private MultipartFile upfile;//업로드된 파일 정보를 저장할 변수
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public MultipartFile getUpfile() {
return upfile;
}
public void setUpfile(MultipartFile upfile) {
this.upfile = upfile;
}
}
package springmvc.fileup.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;
/*
* View 클래스 작성
* 1. AbstractView를 extends
* 2. getContentType() : 응답 content-type을 알려주는 메소드
* renderMergedOutputModel - 응답처리
* 오버라이딩
*
*/
public class DownloadView extends AbstractView{
@Override
public String getContentType() {
return "application/octet-stream";//application인데 stream을 통해서 보내긴 하겠지만 뭔지 모르겟다.따라서 이걸 부르면 다운로드 받게 해준다.
}
//1. 인수 - Map : ModelAndView의 Model을 Map으로 넘겨준다.
@Override
protected void renderMergedOutputModel(Map<String, Object> map,
HttpServletRequest request, HttpServletResponse response) throws Exception {//map은 우리가 modelAndView로 넘기는 값이 들어온다.
//map : fileName 키값으로 다운로드 시킬 파일 명을 받는다.
ServletContext ctx = getServletContext();
//webapplication 경로-> filesystem결로로 바꿔준다.
String realPath = ctx.getRealPath("/upload");///upload : web application Root경로 //파일경오만 바뀌지 다른 것은 그대로 가져다가 재사용가능하다.
String fileName = (String) map.get("fileName");
File downFile = new File(realPath, fileName);
//응답처리
//1. contentType처리
response.setContentType(getContentType());
//2. 다운 로드할 파일 명을 header정보로 설정
response.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"),"8859_1"));//8859-1방식은 라틴방식이다. (한글처리)
//위에서 filename으로 파일이 넘어간다.
OutputStream os = response.getOutputStream();
FileInputStream fi = new FileInputStream(downFile);
//fi.read()한것을 os.write한 효과가 난다. 클라이언트에게 파일이 날아간다.
FileCopyUtils.copy(fi, os);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
Comment : ${requestScope.mto.comment }<br>
업로드된 파일들<br>
<c:forEach items="${requestScope.mto.upfile }" var="file">
<a href="/SpringMVC_04_fileUpload/download.do?fileName=/${file.originalFilename }">
${file.originalFilename }
</a><br>
</c:forEach>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
업로드된 파일<br>
Comment : ${requestScope.comment }<br>
파일 : ${requestScope.fileName }
<hr>
singleUpDTO.do 응답처리<br>
Comment : ${requestScope.sto.comment }<br>
파일 : ${requestScope.sto.upfile.originalFilename }
<hr>
singleUpReq.do 응답처리<br>
Comment : ${requestScope.sto2.comment }<br>
파일 : ${requestScope.sto2.upfile.originalFilename }<br>
<hr>
<c:forEach items="${requestScope.list }" var="file">
${file.originalFilename }<br>
</c:forEach>
</body>
</html>
<?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">
<!-- ViewResolver InternalResourceViewResolver는 항상 마지막에 찾도록 한다.-->
<bean name="vr" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/res/"/>
<property name="suffix" value=".jsp"/>
<!-- ViewResolver 가 두개 이상 일경우 호출 순서 처리한다. -->
<property name="order" value="2"/>
</bean>
<bean name="vr2" class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="1"/>
</bean>
<!-- multipartResolver -->
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- <property name="maxUploadSize" value="1048576"/> --><!--1M : 1024*1024, 1048576 -->
</bean>
<!-- Controller -->
<bean name="fileUploadController" class="springmvc.fileup.ctr.FileUploadController">
<constructor-arg value="D:\apache-tomcat-6.0.35\webapps\SpringMVC_04_fileUpload\upload"/>
</bean>
<!-- View 빈으로 등록 -->
<bean name="downloadView" class="springmvc.fileup.view.DownloadView"/>
</beans>
<!-- /application Root/upload -->
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- DispatcherServlet 등록(front controller) -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 한글 encoding 처리 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<%@ 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>Insert title here</title>
</head>
<body>
<form action="multiUp.do" method="post" enctype="multipart/form-data">
Comment : <input type="text" name="comment"><br>
파일<br>
<input type="file" name="upfile[0]"><br>
<input type="file" name="upfile[1]"><br>
<input type="file" name="upfile[2]"><br>
<input type="submit" value="전송"><br>
</form>
</body>
</html>
<%@ 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>Insert title here</title>
</head>
<body>
파일 업로드 요청<br>
<form action="singleUp.do" method="post" enctype="multipart/form-data">
comment : <input type="text" name="comment"><br>
파일 : <input type="file" name="upfile"><br>
<input type="submit" value="전송">
</form>
<hr>
DTO 이용
<form action="singleUpDTO.do" method="post" enctype="multipart/form-data">
comment : <input type="text" name="comment"><br>
파일 : <input type="file" name="upfile"><br>
<input type="submit" value="전송">
</form>
<hr>
Request 이용<br>
<form action="singleUpReq.do" method="post" enctype="multipart/form-data">
comment : <input type="text" name="comment"><br>
파일 : <input type="file" name="upfile"><br>
<input type="file" name="myupfile"><br>
<input type="file" name="myupfile"><br>
<input type="file" name="myupfile"><br>
<input type="submit" value="전송">
</form>
</body>
</html>
* 결과
'프로그래밍 > Spring MVC' 카테고리의 다른 글
회원가입시 사진추가하기 - 파일 업로드 (0) | 2012.07.05 |
---|---|
FileUpload실습 - DTO를 통해받기, @RequestParam, MultipartHttpServletRequest이용 (0) | 2012.07.04 |
FileUpload(파일 업로드) (0) | 2012.07.04 |
회원정보 수정 폼, 회원정보 수정 처리, 이름으로 검색, 마일리지 범위로 검색(Spring MVC, ibatis 이용) (0) | 2012.07.02 |
로그인, 로그아웃 처리 (0) | 2012.07.02 |