<input type="file" multiple="multiple">ArrayList<MultipartFile> files로 받음Model 반환 ArrayList<String>로 반환<c:forEach> 사용파일 업로드할 폴더 생성
파일 업로드 폼 생성
views 폴더 안에 upload 폴더 만들고
fileUploadForm.jsp파일 업로드 결과 출력 페이지 생성
fileUploadResult.jsp패키지 생성
컨트롤러 생성
FileUploadControllerindex에 추가
spring.servlet.multipart.max-file-sizespring.servlet.multipart.max-request-size
package com.spring_boot_mybatis.project.file;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
// 파일 업로드 폼
@RequestMapping("/fileUploadForm")
public String fileUploadFormView() {
return "upload/fileUploadForm";
}
// 파일 업로드
@RequestMapping("/fileUpload")
public String fileUpLoadView(@RequestParam("uploadFile") MultipartFile file, Model model)
throws IOException {
// 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
String uploadPath = "/Library/springWorkspace/upload/";
// 마지막에 / 있어야함
// 2. 원본 파일 이름 알아오기
String originalFileName = file.getOriginalFilename();
// 3. 파일 이름이 중복되지 않도록 파일 이름 변경 : 서버에 저장할 이름
// UUID 클래스 사용
UUID uuid = UUID.randomUUID();
String savedFileName = uuid.toString() + "_" + originalFileName;
// 4. 파일 생성
File newFile = new File(uploadPath + savedFileName);
// 5. 서버로 전송
file.transferTo(newFile);
// Model 설정 : 뷰 페이지에서 원본 파일 이름 출력
model.addAttribute("originalFileName", originalFileName);
return "upload/fileUploadResult";
}
// 멀티 파일 업로드
@RequestMapping("/fileUploadMultiple")
public String fileUpLoadView(@RequestParam("uploadFileMulti") ArrayList<MultipartFile> files,
Model model) throws IOException {
// 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
String uploadPath = "/Library/springWorkspace/upload/";
// 마지막에 / 있어야함
// 여러 개의 파일 이름 저장할 리스트 생성
ArrayList<String> originalFileNameList = new ArrayList<String>();
for(MultipartFile file :files) {
// 2. 원본 파일 이름 알아오기
String originalFileName = file.getOriginalFilename();
// 파일 이름을 리스트에 추가
originalFileNameList.add(originalFileName);
// 3. 파일 이름이 중복되지 않도록 파일 이름 변경 : 서버에 저장할 이름
// UUID 클래스 사용
UUID uuid = UUID.randomUUID();
String savedFileName = uuid.toString() + "_" + originalFileName;
// 4. 파일 생성
File newFile = new File(uploadPath + savedFileName);
// 5. 서버로 전송
file.transferTo(newFile);
// Model 설정 : 뷰 페이지에서 원본 파일 이름 출력
model.addAttribute("originalFileNameList", originalFileNameList);
}
return "upload/fileUploadMultipleResult";
}
// 파일명 변경하지 않고 파일 업로드
@RequestMapping("/fileOriginNameUpload")
public String fileOriginNameUpLoadView(@RequestParam("uploadFile") MultipartFile file, Model model)
throws IOException {
// 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
String uploadPath = "/Library/springWorkspace/upload/";
// 경록 마지막에 "/" 있어야함
// 2. 원본 파일 이름 알아오기
String originalFileName = file.getOriginalFilename();
// 3. 파일 생성
File newFile = new File(uploadPath + originalFileName);
// 4. 서버로 전송
file.transferTo(newFile);
// Model 설정 : 뷰 페이지에서 원본 파일 이름 출력
model.addAttribute("originalFileName", originalFileName);
return "upload/fileUploadResult";
}
}
(컨트롤러에서 출력할 창)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
// tag library
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 폼</title>
</head>
<body>
<h3>파일 업로드</h3>
<form id="fileUploadForm" method="post" action="<c:url value='/fileUpload'/>"
enctype="multipart/form-data">
파일 : <input type="file" id="uploadFile" name="uploadFile">
<input type="submit" value="업로드">
</form>
<h3>여러 개의 파일 업로드</h3>
<form id="fileUploadFormMulti" method="post"
action="<c:url value='/fileUploadMultiple'/>"
enctype="multipart/form-data">
파일 : <input type="file" id="uploadFileMulti" name="uploadFileMulti" multiple="multiple">
<input type="submit" value="업로드">
</form>
<h3>파일명 변경하지 않고 파일 업로드</h3>
<form id="fileOriginNameUploadForm" method="post"
action="<c:url value='/fileOriginNameUpload'/>"
enctype="multipart/form-data">
파일 : <input type="file" id="uploadFile" name="uploadFile">
<input type="submit" value="업로드">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 결과</title>
</head>
<body>
${originalFileName } 파일을 업로드 하였습니다.<br>
/Library/springWorkspace/upload 폴더에서 확인하세요.
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>여러 개의 파일 업로드 결과</title>
</head>
<body>
${originalFileNameList } 파일을 업로드 하였습니다.<br>
/Library/springWorkspace/upload 폴더에서 확인하세요.<br><br>
<c:forEach var="file" items="${originalFileNameList}">
${file }<br><br>
</c:forEach>
</body>
</html>
파일 및 스트림 복사를 위한 유틸리티 클래스
FileCopyUtils.copy()String encodedFileName = new String (file.getBytes("UTF-8"), "ISO-8859-1");
package com.spring_boot_mybatis.project.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileDonwloadController {
// 파일 목록 보여주기
@RequestMapping("/fileDownloadList")
public ModelAndView fileDownloadList(ModelAndView mv) {
File path = new File("/Library/springWorkspace/upload/");
String[] fileList = path.list();
mv.addObject("fileList", fileList);
mv.setViewName("upload/fileDownloadListView");
return mv;
}
// 파일 다운로드
@RequestMapping("/fileDownload/{file}")
public void fileDownload(@PathVariable String file,
HttpServletResponse response) throws IOException {
File f = new File("/Library/springWorkspace/upload/", file);
// 파일명 인코딩
String encodedFileName = new String (file.getBytes("UTF-8"), "ISO-8859-1");
// file 다운로드 설정
response.setContentType("application/download");
response.setContentLength((int)f.length());
response.setHeader("Content-Disposition", "attatchment;filename=\"" + encodedFileName + "\"");
// 다운로드 시 저장되는 이름은 Response Header의 "Content-Disposition"에 명시
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(f);
FileCopyUtils.copy(fis, os);
// fis.close();
// os.close();
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 다운로드 목록</title>
</head>
<body>
<h3>폴더 내의 모든 파일 목록 출력</h3>
<c:forEach var="file" items="${fileList}">
<a href="<c:url value='/fileDownload/${file }'/>">${file } 파일 다운로드</a><br><br>
</c:forEach>
</body>
</html>






