티스토리 뷰
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
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.20</version>
</dependency>
web.xml
"<multipart-config>" 을 추가합니다.
<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>
controller
package com.thumbnail.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;
import net.coobird.thumbnailator.Thumbnails;
@Controller
public class ThumbnailController {
private String getFileExtension(String fileName) {
if (fileName != null && fileName.contains(".")) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
return "";
}
@RequestMapping(value="/downloadThumbnail", method=RequestMethod.GET)
public void downloadThumbnail(
@RequestParam("fileName") String fileName,
HttpServletResponse response
) throws Exception {
ServletOutputStream out = response.getOutputStream();
String filePath = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles/" + fileName;
File image = new File(filePath);
int lastIndex = fileName.lastIndexOf(".");
String fileNameWithoutExtension = fileName.substring(0, lastIndex);
File thumbnail = new File("/Users/jangjeonghun/eclipse-workspace/uploadedFiles/thumbnail/" + fileNameWithoutExtension + ".png");
if(image.exists()) {
thumbnail.getParentFile().mkdir();
Thumbnails.of(image).size(50,50).outputFormat("png").toFile(thumbnail);
}
FileInputStream in = new FileInputStream(thumbnail);
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();
}
@RequestMapping(value="downloadThumbnailWithoutFile", method=RequestMethod.GET)
public void downloadThumbnailWithoutFile(
@RequestParam("fileName") String fileName,
HttpServletResponse response
) throws Exception {
ServletOutputStream out = response.getOutputStream();
String filePath = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles/" + fileName;
File image = new File(filePath);
if(image.exists()) {
Thumbnails.of(image).size(50,50).outputFormat("png").toOutputStream(out);
} else {
return;
}
byte[] buffer = new byte[1024 * 8];
out.write(buffer);
out.close();
}
@RequestMapping(value="/uploadThumbnail", method=RequestMethod.GET)
public ModelAndView uploadThumbnailGet() {
ModelAndView modelAndView = new ModelAndView("uploadThumbnail");
return modelAndView;
}
@RequestMapping(value="/uploadThumbnail", method=RequestMethod.POST)
public ModelAndView uploadThumbnailPost(@RequestParam("files") MultipartFile[] files) {
ModelAndView modelAndView = new ModelAndView("uploadThumbnail");
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;
}
}
View
<%@ 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>Insert title here</title>
</head>
<body>
<form action="${ contextPath }/uploadThumbnail" method="post" enctype="multipart/form-data">
<label>파일</label><br><br>
<input type="file" name="files" multiple />
<br><br>
<input type="submit" value="send data" />
</form>
<br>
<%-- <p>fileName= ${ fileName }</p>
<c:if test="${ not empty fileName }">
<img src="/downloadThumbnail?fileName=${ fileName }" />
</c:if> --%>
<p>fileName without thumbnail file = ${ fileName }</p>
<c:if test="${ not empty fileName }">
<img src="/downloadThumbnailWithoutFile?fileName=${ fileName }" />
</c:if>
</body>
</html>
728x90
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- system.io
- 스프링 프레임워크(spring framewordk)
- System.Diagnostics
- 상품 등록
- React
- jstl(java standard tag library)-core
- REST API
- await
- .submit()
- java 키워드 정리
- 람다식(lambda expression)
- In App Purchase
- MainActor
- 진수 변환
- 스프링 시큐리티(spring security)
- 스프링 프레임워크(spring framework)
- 제품 등록
- 표현 언어(expression language)
- error-java
- jstl(java standard tag library)
- java-개발 환경 설정하기
- 문자 자르기
- nl2br
- 메이븐(maven)
- 스프링 시큐리티(spring security)-http basic 인증
- java web-mvc
- 인텔리제이(intellij)
- jsp 오픈 소스
- 특정 문자를 기준으로 자르기
- java.sql
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함