티스토리 뷰
package hello.upload.controller;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadVControllerV2 {
@Value("${file.dir}")
private String fileDir;
@GetMapping("/upload")
public String newFile(){
return "upload-form";
}
@PostMapping("/upload")
public String saveFileV1(HttpServletRequest request) throws ServletException, IOException {
log.info("request = {}", request);
String itemName = request.getParameter("itemName");
log.info("itemName = {}", itemName);
Collection<Part> parts = request.getParts();
log.info("parts = {}", parts);
for (Part part : parts) {
log.info("====PART ====");
log.info("name={}",part.getName());
Collection<String> headerNames = part.getHeaderNames();
for(String headerName : headerNames){
log.info("header {} : {} ", headerName, part.getHeader(headerName));
}
//편의 메서드
//content-disposition; fileName
log.info("submittedFilename={}",part.getSubmittedFileName());
log.info("size={}", part.getSize());
//데이터 읽기
InputStream inputStream = part.getInputStream();
String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
log.info("body={}", body);
//파일에 저장하기
if (StringUtils.hasText(part.getSubmittedFileName())){
String fullPath = fileDir + part.getSubmittedFileName();
log.info("파일 저장 fullPath={}", fullPath);
part.write(fullPath);
}
}
return "upload-form";
}
}
Part 주요 메서드
part.getSubmittedFileName() : 클라이언트가 전달한 파일명 part.getInputStream(): Part의 전송 데이터를 읽을 수 있다. part.write(...): Part를 통해 전송된 데이터를 저장할 수 있다.
'dev_공부일지 > spring boot + intelliJ' 카테고리의 다른 글
파일업로드 (4) 업로드와 다운로드 (0) | 2023.12.29 |
---|---|
파일 업로드 (3) 스프링이 제공하는 파일업로드 (0) | 2023.12.29 |
파일 업로드 소개 (0) | 2023.12.25 |
포메터 정리 안되는거 있다. (0) | 2023.12.21 |
스프링이 제공하는 Formatter (1) | 2023.12.21 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 향해99
- JPA
- ArgumentResolver
- 예외처리
- 백엔드 개발자 역량
- 향해플러스
- react실행
- 항해99
- Intercepter
- BindingResult
- 컨트
- 로그인
- filter
- 항해플러스
- HTTP
- thymleaf
- exception
- rejectValue
- jpa api
- 리터럴
- 스프링부트
- React
- 백엔드 개발자 공부
- reject
- Java
- 인터셉터
- 향해플러스백엔드
- hypertexttransferprotocol
- SpringBoot
- 스프링공부
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함