Spring 파일 업로드
파일 업로드
사전 작업
pom.xml
<!-- Servlet -->
<!-- 버전 변경. web.xml 수정 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<!-- 파일 업로드. WAS(Tomcat) 자체 설정 -->
<multipart-config>
<location>C:\\Dev\\upload</location>
<max-file-size>20971520</max-file-size> <!-- 20mb -->
<max-request-size>41943040</max-request-size> <!-- 40mb -->
<file-size-threshold>20971520</file-size-threshold> <!-- 20mb -->
</multipart-config>
</servlet>
servlet-context.xml
<!-- 파일 업로드 bean 설정. id="multipartResolver" 예약어 -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</beans:bean>
파일업로드 작업
iuput의 name의 값을 자바에서 데이터로 받는다
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="uploadFormAction" enctype="multipart/form-data">
<input type="file" name="uploadFile" multiple>
<button type="submit">Submit</button>
</form>
</body>
</html>
package com.demo.controller;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.log4j.Log4j;
@Log4j
@Controller
@RequestMapping("/upload/*")
public class UploadController {
@GetMapping("/uploadForm")
public void uploadForm() {
}
// @PostMapping("/uploadFormAction")
// public void uploadFormPost(MultipartFile[] uploadFile) {
//
// for(MultipartFile multipartFile: uploadFile) {
// log.info("-------------------------------");
// log.info("파일이름 : " + multipartFile.getOriginalFilename());
// log.info("파일크기 : " + multipartFile.getSize());
// }
//
// }
@PostMapping("/uploadFormAction")
public void uploadFormPost(MultipartFile[] uploadFile) {
String uploadFolder = "C:\\Dev\\upload";
for(MultipartFile multipartFile: uploadFile) {
log.info("-------------------------------");
log.info("파일이름 : " + multipartFile.getOriginalFilename());
log.info("파일크기 : " + multipartFile.getSize());
File saveFile = new File(uploadFolder, multipartFile.getOriginalFilename());
try {
multipartFile.transferTo(saveFile); // 파일복사(업로드)
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
댓글남기기