// 파일 업로드
1. cos.jar > 개발 종료
2. commons-fileupload > 많이 사용
3. Servlet 3.0이상 > 파일 업로드 기능 내장
- 설정
~ pom.xml
- 의존성 추가
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>file</artifactId>
<name>FileTest</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>11</java-version>
<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet / JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
<!-- HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.4</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- log4jdbc.log4j2 -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4</artifactId>
<version>1.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>11</source>
<target>11</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
~ web.xml
- webapp 시작 태그 버전 수정
- 파일 업로드 설정 추가
<?xml version="1.0" encoding="UTF-8"?>
<!-- 버전 수정 -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- 파일 업로드 설정 -->
<multipart-config>
<!-- 임시 폴더 지정(C:\OneDrive\class\code\spring\temp) -->
<location>C:\\OneDrive\\class\\code\\spring\\temp</location>
<!-- 첨부파일의 최대 크기 10MB -->
<max-file-size>10485760</max-file-size>
<!-- 한번에 업로드할 수 있는 파일들의 총 크기 50MB -->
<max-request-size>52428800</max-request-size>
<!-- 업로드에 사용할 메모리 용량 10MB -->
<file-size-threshold>10485760</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
</web-app>
~ servlet-context.xml
- 파일 업로드 <bean> 추가
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!--
Enables the Spring MVC @Controller programming model
> @Controller 사용할 수 있게 한다.
-->
<annotation-driven />
<!--
Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory
> resources 폴더 경로의 단축 표현
-->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.test.file" />
<context:component-scan base-package="com.test.controller" />
<!-- 파일 업로드 -->
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></beans:bean>
</beans:beans>
// 단일 파일 업로드 + 다운로드
~ "com.test.controller" > FileController.java
package com.test.controller;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@GetMapping("/add.do")
public String add() {
return "add";
}
@PostMapping("/addok.do")
public String addok(Model model, String txt, MultipartFile attach, HttpServletRequest req) {
//System.out.println("txt: " + txt);
System.out.println(attach.getName()); // <input type="file" name="attach"> 의 name>(태그명)
System.out.println(attach.getOriginalFilename()); // 업로드 파일
System.out.println(attach.getContentType()); // 파일 MIME
System.out.println(attach.getSize()); //사이즈(Byte)
System.out.println(attach.isEmpty()); //존재 유무
//C:\OneDrive\class\code\spring\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FileTest\resources\files
String path = req.getRealPath("/resources/files");
System.out.println(path);
try {
//파일명 중복 방지
//1. 숫자 붙이기
//2. 고유 파일명 만들기
// - 시간_파일명
// - 난수_파일명
//3. UUID, Universally Uizue
// - 네트워크 상에서 고유성이 보장되는 ID를 만들기 위한 표준
// - 시간 + 난수 조합
//System.out.println(System.nanoTime() + "_" + attach.getOriginalFilename());
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
File file = new File(path + "\\" + uuid + "_" + attach.getOriginalFilename());
attach.transferTo(file);
model.addAttribute("txt", txt);
model.addAttribute("filename", uuid + "_" + attach.getOriginalFilename()); // 하드디스크에 저장된 파일명
model.addAttribute("orgfilename", attach.getOriginalFilename()); // 사용자가 올린 파일명ㄴㄴㄴ
} catch (Exception e) {
e.printStackTrace();
}
return "addok";
}
@GetMapping(value = "/download.do", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public ResponseEntity<Resource> downloadFile(@RequestHeader("User-Agent") String userAgent, String filename, HttpServletRequest req) {
String path = req.getRealPath("/resources/files");
Resource resource = new FileSystemResource(path + "\\" + filename);
if (resource.exists() == false) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
String resourceName = resource.getFilename();
// remove UUID
String resourceOriginalName = resourceName.substring(resourceName.indexOf("_") + 1);
HttpHeaders headers = new HttpHeaders();
try {
String downloadName = null;
if (userAgent.contains("Trident")) {
downloadName = URLEncoder.encode(resourceOriginalName, "UTF-8").replaceAll("\\+", " ");
} else if (userAgent.contains("Edge")) {
downloadName = URLEncoder.encode(resourceOriginalName, "UTF-8");
} else {
downloadName = new String(resourceOriginalName.getBytes("UTF-8"), "ISO-8859-1");
}
headers.add("Content-Disposition", "attachment; filename=" + downloadName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new ResponseEntity<Resource>(resource, headers, HttpStatus.OK);
}
}
~ views > add.jsp
> addok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<h1>파일 업로드</h1>
<form method="POST" action="/file/addok.do" enctype="multipart/form-data" id="form1">
<table class="vertical">
<tr>
<th>텍스트</th>
<td><input type="text" name="txt" value="홍길동"></td>
</tr>
<tr>
<th>파일</th>
<td><input type="file" name="attach"></td>
</tr>
</table>
<div>
<button>보내기</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function checkFile(filename, filesize){
const maxsize = 10485760; //10MB
const regex = /^(.*?)\.(exe|sh)$/gi;
if(filesize >= maxsize) {
alert('단일 파일의 크기가 10MB 이하만 가능합니다 !')
return false;
}
if(regex.test(filename)){
alert('해당 파일은 업로드할 수 없습니다.');
return false;
}
return true;
}
//전송되기 바로 직전에 발생하는 이벤트
$('#form1').submit(function() {
let filename = $('input[name=attach]')[0].files[0].name;
//alert(filename);
let filesize = $('input[name=attach]')[0].files[0].size;
//alert(filesize);
if(!checkFile(filename, filesize)) {
//전송 금지!
event.preventDefault();
return false;
}
});
</script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<!-- addok.jsp -->
<h1>결과</h1>
<div class="message" title="txt">${txt}</div>
<div class="message" title="file">
<a href="/file/resources/files/${filename}" download>${filename}</a>
</div>
<div class="message" title="file">
<a href="/file/download.do?filename=${filename}">${orgfilename}</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
// 다중 파일 업로드
package com.test.controller;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@GetMapping("/add.do")
public String add() {
return "add";
}
@PostMapping("/multiaddok.do")
public String multiaddok(Model model, String txt, MultipartFile[] attach, HttpServletRequest req) {
for (MultipartFile file : attach) {
System.out.println(file.getName()); // <input type="file" name="attach"> 의 name>(태그명)
System.out.println(file.getOriginalFilename()); // 업로드 파일
System.out.println(file.getContentType()); // 파일 MIME
System.out.println(file.getSize()); //사이즈(Byte)
System.out.println(file.isEmpty()); //존재 유무
System.out.println();
try {
UUID uuid = UUID.randomUUID();
String filename = uuid + "_" + file.getOriginalFilename();
file.transferTo(new File(req.getRealPath("/resources/files") + "\\" + filename));
} catch (Exception e) {
e.printStackTrace();
}
}
model.addAttribute("txt", txt);
return "addok";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<h1>다중 파일 업로드(multiple)</h1>
<form method="POST" action="/file/multiaddok.do" enctype="multipart/form-data" id="form2">
<table class="vertical">
<tr>
<th>텍스트</th>
<td><input type="text" name="txt" value="홍길동"></td>
</tr>
<tr>
<th>파일</th>
<td><input type="file" name="attach" multiple></td>
</tr>
</table>
<div>
<button>보내기</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function checkFile(filename, filesize){
const maxsize = 10485760; //10MB
const regex = /^(.*?)\.(exe|sh)$/gi;
if(filesize >= maxsize) {
alert('단일 파일의 크기가 10MB 이하만 가능합니다 !')
return false;
}
if(regex.test(filename)){
alert('해당 파일은 업로드할 수 없습니다.');
return false;
}
return true;
}
$('#form2').submit(function() {
//let filename = $('input[name=attach]')[0].files[0].name;
//let filesize = $('input[name=attach]')[0].files[0].size;
let totalsize = 0;
Array.from($('input[name=attach]')[1].files).forEach(file => {
if(!checkFile(file.name, file.size)) {
event.preventDefault();
return false;
}
totalsize += file.size;
});
if(totalsize >= 52428800) {
alert('총 파일 크기의 합 50MB 이하만 가능합니다.');
event.preventDefault();
return false;
}
});
</script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<!-- addok.jsp -->
<h1>결과</h1>
<div class="message" title="txt">${txt}</div>
<div class="message" title="file">
<a href="/file/resources/files/${filename}" download>${filename}</a>
</div>
<div class="message" title="file">
<a href="/file/download.do?filename=${filename}">${orgfilename}</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
// 다중 파일 업로드(File Drop)
package com.test.controller;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@GetMapping("/add.do")
public String add() {
return "add";
}
@PostMapping("/multiaddok.do")
public String multiaddok(Model model, String txt, MultipartFile[] attach, HttpServletRequest req) {
for (MultipartFile file : attach) {
System.out.println(file.getName()); // <input type="file" name="attach"> 의 name>(태그명)
System.out.println(file.getOriginalFilename()); // 업로드 파일
System.out.println(file.getContentType()); // 파일 MIME
System.out.println(file.getSize()); //사이즈(Byte)
System.out.println(file.isEmpty()); //존재 유무
System.out.println();
try {
UUID uuid = UUID.randomUUID();
String filename = uuid + "_" + file.getOriginalFilename();
file.transferTo(new File(req.getRealPath("/resources/files") + "\\" + filename));
} catch (Exception e) {
e.printStackTrace();
}
}
model.addAttribute("txt", txt);
return "addok";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
#attach-zone {
border: 1px solid var(--border-color);
background-color: var(--back-color);
width: 300px;
height: 150px;
overflow: auto;
}
#attach-zone .item {
display: flex;
justify-content: space-between;
font-size: 14px;
margin: 5px 10px;
}
</style>
</head>
<body>
<h1>다중 파일 업로드(File Drop)</h1>
<form method="POST" action="/file/multiaddok.do" enctype="multipart/form-data" id="form3">
<table class="vertical">
<tr>
<th>텍스트</th>
<td><input type="text" name="txt" value="홍길동"></td>
</tr>
<tr>
<th>파일</th>
<td>
<div id="attach-zone"></div>
<input type="file" name="attach" id="attach3" style="display:none;">
</td>
</tr>
</table>
<div>
<button>보내기</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function checkFile(filename, filesize){
const maxsize = 10485760; //10MB
const regex = /^(.*?)\.(exe|sh)$/gi;
if(filesize >= maxsize) {
alert('단일 파일의 크기가 10MB 이하만 가능합니다 !')
return false;
}
if(regex.test(filename)){
alert('해당 파일은 업로드할 수 없습니다.');
return false;
}
return true;
}
$('#attach-zone')
.on('dragenter', function(e) {
e.preventDefault();
e.stopPropagation();
})
.on('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
$(this).css('background-color', 'gold');
})
.on('dragleave', function(e) {
e.preventDefault();
e.stopPropagation();
$(this).css('background-color', 'var(--back-color)');
})
.on('drop', function(e) {
$(this).empty();
e.preventDefault();
const files = e.originalEvent.dataTransfer.files;
if(files != null & files != undefined) {
let temp = '';
for (let i=0; i<files.length; i++) {
//console.log(files[i].name);
let f = files[i];
let filename = f.name;
let filesize = f.size / 1024 / 1024; //MB 변환
filesize = filesize < 1 ? filesize.toFixed(2) : filesize.toFixed(1);
temp += `
<div class="item">
<span>\${filename}</span>
<span>\${filesize}MB</span>
</div>
`;
}// for
$(this).append(temp);
}//if
$(this).css('background-color', 'var(--back-color)');
$('#attach3').prop('files', files);
})
</script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<!-- addok.jsp -->
<h1>결과</h1>
<div class="message" title="txt">${txt}</div>
<div class="message" title="file">
<a href="/file/resources/files/${filename}" download>${filename}</a>
</div>
<div class="message" title="file">
<a href="/file/download.do?filename=${filename}">${orgfilename}</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
※ 아파치 톰캣 다운로드 > 특수문자 해결
- "Servers" > server.xml > Connector connectionTimeout="20000" maxParameterCount="1000" port="8091" protocol="HTTP/1.1" redirectPort="8443" 뒤에 relaxedQueryChars="[]()^|"" 추가
'서버 > Spring' 카테고리의 다른 글
[Spring Security] 회원가입, 자동 로그인 (0) | 2023.06.22 |
---|---|
[Spring Security] 로그인, 로그아웃, 계정 정보 (0) | 2023.06.21 |
[스프링(Spring)] MyBatis (1) | 2023.06.16 |
[스프링(Spring)] MVC 에러 처리 (0) | 2023.06.16 |
[스프링(Spring)] MVC 데이터 수신 및 전송 (1) | 2023.06.15 |