티스토리 뷰

728x90
반응형

개발 환경

java 21.0.4 2024-07-16 LTSJava(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)

Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)

 

Tomcatv 10.1

EclipseVersion: 2024-06 (4.32.0)Build id: 20240606-1231


pom.xml

dependency: "commons-fileupload2-jakarta-servlet6"를 추가합니다.

<!--https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.1.11</version>
</dependency>
<!--https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>6.1.11</version>
</dependency>

<!--https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope> <!-- 배포 시에는 포함되지 않습니다. -->
</dependency>

<!--https://mvnrepository.com/artifact/jakarta.servlet.jsp.jstl/jakarta.servlet.jsp.jstl-api -->
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.web/jakarta.servlet.jsp.jstl -->
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>3.0.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-fileupload2-jakarta-servlet6 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-fileupload2-jakarta-servlet6</artifactId>
    <version>2.0.0-M2</version>
</dependency>

web.xml

"<multipart-config>" 설정을 추가합니다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://jakarta.ee/xml/ns/jakartaee"
	xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
	id="WebApp_ID" version="5.0">
	<display-name>COM.FILE</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.jsp</welcome-file>
		<welcome-file>default.htm</welcome-file>
	</welcome-file-list>
	
	<!-- ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

	<!-- DispatcherServlet -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:dispatcherServlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>

		<multipart-config>
			<location>/tmp</location> <!-- 임시 파일 저장 경로 -->
			<max-file-size>5242880</max-file-size> <!-- 파일당 최대 크기 5MB -->
			<max-request-size>20971520</max-request-size> <!-- 전체 요청 최대 크기 20MB -->
			<file-size-threshold>0</file-size-threshold>
		</multipart-config>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 한글 깨짐 설정(텍스트 인코딩) -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

Controller

FileManagement.java 파일을 생성합니다.

package com.file.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

@Controller
public class FileManagement {

	// 파일 확장자를 추출하는 메서드
    private String getFileExtension(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return "";
    }
	
	@RequestMapping(value="/fileUpload", method=RequestMethod.GET)
	public String fileUploadGet() {
		
		return "fileUpload";
	}
	
	@RequestMapping(value="/fileUpload", method=RequestMethod.POST)
	public ModelAndView fileUploadPost(@RequestParam("files") MultipartFile[] files) {
//		if (files.length == 0) {
//			업로드할 파일을 선택해주세요.
//		}
		
		ModelAndView modelAndView = new ModelAndView("fileUpload");
		String uploadDir = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles";
		
		List<String> failedFiles = new ArrayList<String>();
		List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "gif", "pdf");
		
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            
            try {
                Path uploadPath = Paths.get(uploadDir);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                
                String originalFileName = file.getOriginalFilename();
    			String fileExtension = getFileExtension(originalFileName);

    			// 확장자 제한 체크
    			if (!allowedExtensions.contains(fileExtension.toLowerCase())) {
    				failedFiles.add(String.format("%s(허용되지 않는 확장자 파일)", originalFileName));
    				continue;
    			}
    			
    			// 파일명 중복 방지
                String uniqueFileName = String.format("%s_%s", UUID.randomUUID().toString(), originalFileName);

                // 파일 저장
                Path filePath = uploadPath.resolve(uniqueFileName);
                Files.copy(file.getInputStream(), filePath);
                
                modelAndView.addObject("fileName", uniqueFileName);
            } catch (IOException e) {
                e.printStackTrace();
                failedFiles.add(String.format("%s(업로드 실패)", file.getOriginalFilename()));
            }
        }
        
        if(failedFiles.isEmpty()) {
        	modelAndView.addObject("message", "파일 업로드가 완료 되었습니다.");
        } else {
        	modelAndView.addObject("message", String.join(",", failedFiles));
        }

		return modelAndView;
	}
	
	@RequestMapping(value="/fileDownload", method=RequestMethod.GET)
	public void fileDownload(
			@RequestParam("fileName") String fileName,
			HttpServletResponse response
	) throws Exception {
		String downloadFile = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles/" + fileName;
		
		ServletOutputStream out = response.getOutputStream();
		File file = new File(downloadFile);
		
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Content-disposition", "attachment; fileName="+fileName);
		
		FileInputStream in = new FileInputStream(file);
		byte[] buffer = new byte[1024 * 8];
		while(true) {
			int count = in.read(buffer);
			if(count == -1) { break; }
			
			out.write(buffer, 0, count);
		}
		
		in.close();
		out.close();
	}
	
	
}

View

fileUpload.jsp 파일을 생성합니다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="jakarta.tags.core"%>
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로</title>
</head>
<body>
	<h1>this is a file page.</h1>
	<h1 style="color:red">${ message }</h1>
	<form action="${ contextPath }/fileUpload" method="post" enctype="multipart/form-data">
		<label>파일</label><br><br>
		<input type="file" name="files" multiple /><br><br>
		<!-- <input type="file" name="files" /><br><br> -->
		
		<input type="submit" value="send data" />
	</form>
	<br>
	
	fileName= ${ fileName }
	<c:if test="${ not empty fileName }">
		<img src="/fileDownload?fileName=${ fileName }" />
	</c:if>
</body>
</html>
728x90
반응형