Spring 다중 파일 업로드
- 스프링의 CommonsMultipartResolver 클래스 : 여러 개의 파일을 한꺼번에 업로드 가능
CommonsMultipartResolver 클래스 속성
property | description |
maxUploadSize | 최대로 업로드가 가능한 파일의 크기를 설정 |
maxInMemorySize | 디스크에 임시 파일을 생성하기 전 메모리에 보관할 수 있는 최대 바이트 크기를 설정 |
defaultEncodin | (UTF-8) 전달되는 매개변수의 인코딩을 설정 |
** 라이브러리 함수는 어노테이션으로 객체 생성 불가능.
다중파일업로드 실습#1
pom.xml
...
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>promvn02r</artifactId>
<name>promvn02r</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
...
<!-- 다중파일업로드 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<!-- 썸네일이미지 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- 이메일 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.3</version>
</dependency>
...
servelt-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xsi:schemaLocation="http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/mvc" >
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.spring.promvn02r" />
<!--멀티파트리졸버-->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="52428800" />
<beans:property name="maxInMemorySize" value="1000000" />
<beans:property name="defaultEncoding" value="utf-8" />
</beans:bean>
</beans:beans>
com.spring.promvn02r.ex01 패키지
FileUploadController.java
package com.spring.promvn02r.ex01;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController {
private static final String CURR_IMAGE_REPO_PATH = "c:\\spring\\image_repo";
@RequestMapping(value="/form")
public String form() {
return "uploadForm";
}
@RequestMapping(value="/upload", method=RequestMethod.POST)
public ModelAndView upload(MultipartHttpServletRequest multipartRequest, HttpServletResponse response) throws Exception {
multipartRequest.setCharacterEncoding("utf-8");
Map map = new HashMap();
Enumeration enu = multipartRequest.getParameterNames();
while(enu.hasMoreElements()) {
String name = (String) enu.nextElement();
String value = multipartRequest.getParameter(name);
System.out.println(name + ", " + value);
map.put(name, value);
}
List fileList = fileProcess(multipartRequest);
map.put("fileList", fileList);
ModelAndView mav = new ModelAndView();
mav.addObject("map", map);
mav.setViewName("result");
return mav;
}
private List<String> fileProcess(MultipartHttpServletRequest multipartRequest) throws Exception {
List<String> fileList = new ArrayList<String>();
Iterator<String> fileNames = multipartRequest.getFileNames();
while(fileNames.hasNext()) {
String fileName = fileNames.next();
System.out.println("fileName : " + fileName);
MultipartFile mFile = multipartRequest.getFile(fileName);
System.out.println("mfile : " + mFile);
String originalFileName = mFile.getOriginalFilename();
System.out.println("originalFileName : " + originalFileName);
fileList.add(originalFileName);
File file = new File(CURR_IMAGE_REPO_PATH + "\\" + fileName);
if(mFile.getSize()!=0) { // File Null Check
if(!file.exists()) {
if(file.getParentFile().mkdirs()) {
file.createNewFile();
}
}
mFile.transferTo(new File(CURR_IMAGE_REPO_PATH + "\\" + originalFileName));
}
}
return fileList;
}
}
com.spring.promvn02r.ex01 패키지
FileDownloadController.java
package com.spring.promvn02r.ex01;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class FileDownloadController {
private static String CURR_IMAGE_REPO_PATH = "c:\\spring\\image_repo";
@RequestMapping("/download")
public void download(@RequestParam("imageFileName") String imageFileName, HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
String downFile = CURR_IMAGE_REPO_PATH + "\\" + imageFileName;
File file = new File(downFile);
response.setHeader("Cache-Control", "no-cache");
response.addHeader("Content-disposition", "attachment: fileName=" + imageFileName);
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024 * 8];
while(true) {
int count = in.read(buffer);
System.out.println(count);
if(count == -1) break;
out.write(buffer, 0, count);
}
in.close();
out.close();
}
}
webapp-WEB-INF-views
result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>결과창</title>
</head>
<body>
<h1>업로드가 완료되었습니다.</h1>
<label>아이디 : </label>
<input type="text" name="id" value="${map.id}" readonly><br>
<label>이름 : </label>
<input type="text" name="name" value="${map.name}" readonly><br>
<div class="result-images">
<c:forEach var="imageFileName" items="${map.fileList}" >
<%-- <img src="${pageContext.request.contextPath}/donwload?imageFileName=${imageFileName}" style="width:150px"> --%>
<img src="${pageContext.request.contextPath}/download?imageFileName=${imageFileName}">
<br><br><br>
</c:forEach>
</div>
<p><a href='${pageContext.request.contextPath}/form'>다시 업로드 하기</a></p>
</body>
</html>
uploadForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 하기</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var cnt=1;
function fn_addFile() {
$("#d_file").append("<br>"+"<input type='file' name='file"+cnt+"' />");
cnt++;
}
</script>
</head>
<body>
<h1>파일 업로드 하기</h1>
<form method="post" action="${contextPath}/upload" enctype="multipart/form-data">
<label>아이디 : </label>
<input type="text" name="id"><br>
<label>이름 : </label>
<input type="text" name="name"><br>
<input type="button" value="파일추가" onClick="fn_addFile()" /><br>
<div id="d_file">
</div>
<input type="submit" value="업로드" />
</form>
</body>
</html>
-- 결과 --
다중파일업로드 (썸네일)실습#2
com.spring.promvn02r.ex01 패키지의 FileDownloadController.java에서 @Controller 주석처리 후,
com.spring.promvn02r.ex02 패키지 생성
FileDownloadController.java
package com.spring.promvn02r.ex02;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import net.coobird.thumbnailator.Thumbnails;
@Controller()
public class FileDownloadController {
private static String CURR_IMAGE_REPO_PATH = "c:\\spring\\image_repo";
@RequestMapping("/download")
protected void download(@RequestParam("imageFileName") String imageFileName, HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
String filePath = CURR_IMAGE_REPO_PATH + "\\" + imageFileName;
File image = new File(filePath);
int lastIndex = imageFileName.lastIndexOf(".");
String fileName = imageFileName.substring(0, lastIndex);
File thumbnail = new File(CURR_IMAGE_REPO_PATH + "\\" +"thumbnail" + "\\" + fileName + ".png");
if(image.exists()) {
thumbnail.getParentFile().mkdirs();
Thumbnails.of(image).size(50,50).outputFormat("png").toFile(thumbnail);
}
FileInputStream in = new FileInputStream(thumbnail);
byte[] buffer = new byte[1024 * 8];
while(true) {
int count = in.read(buffer);
if(count == -1) break;
out.write(buffer, 0, count);
}
in.close();
out.close();
}
}
-- 결과 --
'Spring' 카테고리의 다른 글
Spring #13 : 인터셉터(Interceptor) (230131) (0) | 2023.01.31 |
---|---|
Spring #12 : 이메일 기능 (230131) (0) | 2023.01.31 |
Spring #9 : 메이븐과 스프링 STS (230125) (0) | 2023.01.25 |
Spring #8 : 스프링 트랜잭션(230120) (0) | 2023.01.20 |
Spring #7 : 스프링-마이바티스 연동(추가)(230120) (0) | 2023.01.20 |
댓글