Spring 파일 업로드
설정
- Servers > Tomcat > Server.xml
- pom.xml
- root-context.xml
JSP
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<style>
</style>
</head>
<body>
<a href="fileList.do">파일 리스트 보기</a>
<br/>
<h3>단일 파일 업로드</h3>
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="text" name="title"/>
<input type="file" name="uploadFile"/>
<input type="submit" value="전송"/>
</form>
<br/>
<hr/>
<br/>
<h3>멀티 파일 업로드</h3>
<form action="multiupload.do" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFiles" multiple="multiple"/>
<input type="submit" value="전송"/>
</form>
</body>
<script></script>
</html>
- list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<style>
</style>
</head>
<body>
<!-- 일반파일의 경우 : link를 걸면 다운로드 됨(뷰어가 있는 경우 제외) -->
<a href="/photo/test.zip">다운로드</a>
<br/>
<c:if test="${list.size()==0}">
<h3>업로드된 사진이 없습니다.</h3>
</c:if>
<c:if test="${list.size()>0}">
<c:forEach items="${list}" var="path">
<img src="${path}" width="500"/>
<a href="delete?file=${fn:split(path,'/')[1]}">삭제</a>
<br/>
</c:forEach>
</c:if>
</body>
<script></script>
</html>
- Controller
package kr.co.gudi.controller;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import kr.co.gudi.service.FileService;
@Controller
public class FileController {
// 재활용하여 메모리 적게 사용
@Autowired FileService service;
Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value="/")
public String home() {
logger.info("index.jsp로 이동");
return "index";
}
@RequestMapping(value="/upload.do", method = RequestMethod.POST)
public String uploard(MultipartFile uploadFile, @RequestParam String title) {
logger.info("일반 파라메터 : " + title);
service.upload(uploadFile);
return "redirect:/fileList.do";
}
@RequestMapping(value="/fileList.do")
public String fileList(Model model) {
logger.info("fileList 요청");
ArrayList<String> list = service.fileList();
logger.info("list size : "+list.size());
model.addAttribute("list", list);
return "list";
}
@RequestMapping(value="/multiupload.do", method = RequestMethod.POST)
public String multiupload(MultipartFile[] uploadFiles) {
logger.info("file size : "+uploadFiles.length);
service.multiupload(uploadFiles);
return "redirect:/fileList.do";
}
@RequestMapping(value="/delete")
public String delete(@RequestParam String file) {
logger.info("deleteFile : "+file);
service.delete(file);
return "redirect:/fileList.do";
}
}
- Service
package kr.co.gudi.service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileService {
Logger logger = LoggerFactory.getLogger(getClass());
String root = "C:/img/upload/";
public void upload(MultipartFile file) {
//1. 파일명 추출
String fileName = file.getOriginalFilename();
//1-2. 겹치지 않는 파일명 생성
//원본파일에서 확장자 추출(photo.jpg)
int index = fileName.lastIndexOf(".");
String ext = fileName.substring(index);
//새로운 파일명 생성(현재시간 기준으로)
long time = System.currentTimeMillis();
String newFileName = time+ext;
//새파일명 + 확장자
logger.info("fileName : "+fileName+"=>"+newFileName);
//2. 파일 저장
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(root+newFileName);
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<String> fileList() {
ArrayList<String> pathList = new ArrayList<String>();
File[] files = new File(root).listFiles();
for(File file : files) {
logger.info("file name : "+file.getName());
pathList.add("/photo/"+file.getName());
}
return pathList;
}
public void multiupload(MultipartFile[] uploadFiles) {
for (MultipartFile file : uploadFiles) { //파일을 하나씩 꺼내서
upload(file); //upload 메서드 호출
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void delete(String file) {
//1. File 객체 생성
File delFile = new File(root+file);
//2. 지울 파일이 있는지 확인
if(delFile.exists()) {
//3. 있으면 삭제
delFile.delete();
}
}
}
'코딩도전기 > Spring' 카테고리의 다른 글
CODO Day45_Spring(AJAX) (0) | 2023.04.05 |
---|---|
CODO Day44_Spring(PhotoBoard) (0) | 2023.04.04 |
CODO Day42_Spring(BoardApp) (0) | 2023.03.31 |
CODO Day41_Spring(MemberApp) (0) | 2023.03.30 |
CODO Day40_Spring(MyBatis) (0) | 2023.03.28 |