코딩기록
Day - 43 [Spring] FileService 본문
1) 설정
servers -> server.xml

2) pom.xml (Aspect J 위)

3) root-context.xml

JSP
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<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>
<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>
<hr/>
<h3>멀티 파일 업로드</h3>
<form action="multiupload.do" method="post" enctype="multipart/form-data">
<tr>
<td>
<input type="file" name="uploadFiles" multiple="multiple"/>
<input type="submit" value="전송"/>
</td>
</tr>
</form>
</body>
<script></script>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<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> -->
<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>
FileController
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<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> -->
<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>
FileService
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) {
String fileName = file.getOriginalFilename();// 1. 파일명 추출
// 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. 파일 저장(JAVA NIO)
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);
if(delFile.exists()) {// 2. 지울 파일이 있는지 확인
delFile.delete();// 3. 있으면 삭제
}
}
}

'study' 카테고리의 다른 글
| 230531 [Spring BOOT] 12_api (0) | 2023.05.31 |
|---|---|
| [Spring Boot] 1일차 01~05.Mybatis (0) | 2023.05.24 |
| Day - 44 [Spring] mybatis 다시 (0) | 2023.04.05 |
| Day - 44 [Spring] File Service - AJAX (0) | 2023.04.05 |
| Day - 43 [Spring] 08_photoBoard (0) | 2023.04.04 |