21. 파일 업로드 방식
<form>
태그를 이용하는 방식: 브라우저의 제한이 없어야 하는 경우에 사용- 1.페이지 이동과 동시에 첨부파일을 업로드하는 방식 (동기형!)
- 2.
<iframe>
을 이용해 화면의 이동 없이 첨부파일을 처리하는 방식 - Ajax를 이용하는 방식: 첨부파일을 별도로 처리하는 방식
- 1.
<input type="file">
을 이용하고 Ajax로 처리하는 방식 - 2. HTML5의 Drag And Drop 기능이나 jQuery 라이브러리를 이용해 처리하는 방식
21.2 form 방식의 파일 업로드방식의 파일 업로드
UploadController.java
package site.levinni.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
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.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.log4j.Log4j;
@Controller
@Log4j
public class UploadController implements ServletContextAware{
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
// TODO Auto-generated method stub
this.servletContext = servletContext;
}
@GetMapping("upload")
public void uploadForm() {
log.info("upload get...");
}
@PostMapping("uploadAction")
public void upload(MultipartFile[] files, Model model) throws IllegalStateException, IOException {
String uploadFolder = "d:/upload";
log.info("upload post...");
for(MultipartFile mf : files) {
log.info("..................................................");
log.info("upload file name :: " + mf.getOriginalFilename());
log.info("upload file size :: " + mf.getSize());
File saveFile = new File(uploadFolder, mf.getOriginalFilename());
mf.transferTo(saveFile);
}
}
}
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>2021. 4. 14.오후 3:32:42</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="uploadAction">
<input type="file" name="files" multiple> <!-- 컨트롤러의 파라미터랑 name 맞춰야 함. -->
<button>전송</button>
</form>
</body>
</html>
'스프링 Spring' 카테고리의 다른 글
Part 5. AOP와 트랜잭션 21. 04. 14. (0) | 2021.04.15 |
---|---|
댓글 더보기 처리 이어서 21. 04. 14. (0) | 2021.04.15 |
21. 04. 13. (0) | 2021.04.14 |
21. 04. 12. (0) | 2021.04.13 |
21. 04. 07. (0) | 2021.04.08 |