spring mvc 에서 파일 업로드 다운로드 하는 방법!
1. 파일 업로드
1-1 라이브러리 추가 (pom.xml에 추가)
commons-fileupload, commons-io.jar 추가하기
<!-- 파일업로드용 라이브러리 2개 추가 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
1-2 MultipartResolver 추가 (root-context.xml)
<!-- 파일 업로드 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1"></property> <!-- '-1' 은 파일크기 무제한 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
1-3 파일 업로드 view(jsp) 작업
간단하게 파일 uploadForm과 uploadPro 만들고
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>uploadform</title>
</head>
<body>
<h2> File Upload</h2> //post!! multipart 로 보내기!!
<form action="/upload/uploadPro" method="post" enctype="multipart/form-data">
message : <input type="text" name="msg" /> <br/>
file : <input type="file" name="img" /> <br/>
message : <input type="submit" value="전송" /> <br/>
</form>
</body>
</html>
-------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>upload Pro</title>
</head>
<body>
</body>
</html>
1-4 파일 업로드 컨트롤러 작업
파일업로드 작업
MultipartHttpServletRequest 인터페이스
* 주요 메서드
Iterator<String> getFileNames() : 업로드된 파일들의 파라미터 명 리턴
MultipartFile getFile(String name) : 파라미터명이 name인 파일 리턴
List<MultipartFile> getFiles(String name) : 파라미터명이 name인 업로드 파일 정보 목록 리턴
* 작업 순서
- 처리 매핑 메서드에 매개변수 MultipartHttpServletRequest 지정
- request에서 파일 정보 꺼내담기
- 파일 저장 경로 + 새파일명 만들어 File 객체 만들기 (파일 이름 중복 안되게)
- .transferTo() 메서드로 파일 저장
package com.board.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
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 org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import lombok.extern.log4j.Log4j;
@Controller
@RequestMapping("/upload/*")
@Log4j
public class UploadController {
@GetMapping("uploadForm")
public void upload() {
log.info("upload form!!!!!!!!!!!!!!");
}
@PostMapping("uploadPro")
public void uploadPro(String msg, MultipartHttpServletRequest request) { // msg(text), img(file)
log.info("*********upload pro*************");
log.info("********* msg : " + msg );
//log.info("********* img content type : " + request.getContentType());
//log.info("********* img : " + request.getFile("img")); // 파일 정보 꺼내기
try {
// 전송한 파일 정보 꺼내기
MultipartFile mf = request.getFile("img");
log.info("****************** original file name : " + mf.getOriginalFilename());
log.info("****************** file size : " + mf.getSize());
log.info("****************** file contentType: " + mf.getContentType());
// 파일 저장 경로
String path = request.getRealPath("/resources/save");
log.info(" save path : "+ path);
// 새파일명 생성
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(); // 하이픈 다 빼버림 대문자로
log.info("***********uuid : " + uuid);
// 업로드한 파일 확장자만 가져오기
String orgName= mf.getOriginalFilename();
// beach.jpg -> .jpg만 두고 나머지는 지움
String ext = orgName.substring(orgName.lastIndexOf("."));
// 저장할 파일명
String newFileName = uuid + ext;
log.info("*****new fileName : " + newFileName);
//저장할 파일 전체 경로
String imgPath = path + "\\" + newFileName;
log.info("****imgPath : " + imgPath);
// 파일저장
File copyFile = new File(imgPath);
mf.transferTo(copyFile);
}catch(IOException e){
e.printStackTrace();
}
}
}
'WEB Creator > [Spring]' 카테고리의 다른 글
[Spring] Filter와 Interceptor의 차이점 (0) | 2022.09.08 |
---|---|
[Spring] @Controller와 @RestController (0) | 2022.08.31 |
[Spring] File Download (0) | 2022.08.25 |