[스프링 -4]Spring 파일 업로드 하기 (fileupload)

2022. 7. 14. 21:15· 기존(310)/🏀Spring
목차
  1. 1. JSP 페이지에 업로드할 파일 구현하기 ( upload.jsp)
  2. 1-1 JSP 페이지에 업로드할 파일 구현하기 (upload_result.jsp)
  3. 2. action 으로 전송될 controll class 구현하기
  4. 3. Servlet-context.xml bean 추가
  5. 3.여기까지 해서 실행시켜보면 이렇게 파일 업로드가

1. JSP 페이지에 업로드할 파일 구현하기 ( upload.jsp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
 
<form id="form1" action="/spring/upload/upload.do" method="post" enctype="multipart/form-data" target="iframe1">
//enctype="multipart/form-data" 꼭 설정해주세요
 
 
<input type="file" name="file">
 
<input type="submit" value="업로드">
 
</form>
 
<iframe name="iframe1"></iframe>
//업로드 완료되면 iframe 보여주기 위해 추가
Colored by Color Scripter
cs

1-1 JSP 페이지에 업로드할 파일 구현하기 (upload_result.jsp)

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
파일이 업로드 되었습니다<br>
파일명 : ${saved_name}
</body>
</html>
Colored by Color Scripter
cs

 

2. action 으로 전송될 controll class 구현하기

 

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.example.spring.controller;
 
import java.io.File;
import java.util.UUID;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class UploadController {
 
    @Resource(name = "upload_path") // Servlet-content.xml 의 이름과 맞아야함! bean등록필수
    String upload_path;    
    
    
    @RequestMapping("/upload/input.do")
    public String input() {
        return "upload/input";
    }
    
    
    @RequestMapping("/upload/upload.do")
    public ModelAndView upload(MultipartFile file,ModelAndView mav) throws Exception {
        
        //첨부파일 이름
        String savedName = file.getOriginalFilename();
        // uuid 를 추가한 파일이름
        savedName = uploadFile(savedName,file.getBytes());
        //jsp 페이지 이름
        mav.setViewName("upload/upload_result");
        //jsp 페이지 전달할 변수 저장
        mav.addObject("saved_name",savedName);
        //page 로 포워드
        return mav; // upload/upoad_result 페이지로 이동
        
    }
    
    public String uploadFile(String originalName,byte[] fileData) throws Exception{
        
        //uuid 생성
        
        UUID uid = UUID.randomUUID(); //랜덤으로 붙힐 숫자 생성
        String savedName = uid.toString()+"_"+originalName; //저장할이름에 랜덤숫자+파일이름
        File target = new File(upload_path,savedName);
        //파일 복사
        FileCopyUtils.copy(fileData, target);
        return savedName; 
        
    }
    
}
 
 
Colored by Color Scripter
cs

 

 

3. Servlet-context.xml bean 추가

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    <!-- 파일업로드에 필요한 bean -->
 
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 
<!-- 파일업로드 최대 용량(byte) -->
 
<beans:property name="maxUploadSize"
value="10485760" />
 
</beans:bean>
 
<!-- 첨부파일을 저장할 디렉토리 설정 -->
 
<beans:bean id="upload_path" class="java.lang.String">
 
<beans:constructor-arg value="C:\Users\cas90\Desktop\upload" />
 
</beans:bean>
Colored by Color Scripter
cs

 

 

3.여기까지 해서 실행시켜보면 이렇게 파일 업로드가

완료 됩니다..

 

저작자표시 (새창열림)

'기존 > 🏀Spring' 카테고리의 다른 글

[스프링 -6]Spring 네이버 로그인하기 (네아로)  (0) 2022.07.14
[스프링 -5]Spring 상품리스트화면 구현하기 (product)  (0) 2022.07.14
[스프링 -3]Spring 중복확인 Ajax요청 (아이디 중복확인)  (0) 2022.07.14
[스프링 -2]Spring 로그인하기 (DB저장,mapper,mybatis)  (0) 2022.07.14
[스프링 -1]Spring 회원가입하기 (DB저장,mapper,mybatis)  (0) 2022.07.14
  1. 1. JSP 페이지에 업로드할 파일 구현하기 ( upload.jsp)
  2. 1-1 JSP 페이지에 업로드할 파일 구현하기 (upload_result.jsp)
  3. 2. action 으로 전송될 controll class 구현하기
  4. 3. Servlet-context.xml bean 추가
  5. 3.여기까지 해서 실행시켜보면 이렇게 파일 업로드가
'기존(310)/🏀Spring' 카테고리의 다른 글
  • [스프링 -6]Spring 네이버 로그인하기 (네아로)
  • [스프링 -5]Spring 상품리스트화면 구현하기 (product)
  • [스프링 -3]Spring 중복확인 Ajax요청 (아이디 중복확인)
  • [스프링 -2]Spring 로그인하기 (DB저장,mapper,mybatis)
조각남자
조각남자
프로그래밍 기술 및 저장소
조각남자프로그래밍 기술 및 저장소
조각남자
조각남자
조각남자
전체
오늘
어제
  • 전체 보기
    • Java
      • Spring
    • 기존
      • 🏀Jsp
      • 🏀Spring
      • 🏀Pom.xml
      • 🏀SpringBoot
      • 🏀JavaExcption
      • 🏀JavaDB
      • 🏀SpringBootCloneWebSite
      • 🏀SptringDependency
      • 🏀JpaEnvorinoment
      • 🏀Thymeleaf
      • 🏀Node
      • 🏀Pyton
      • 🏀DataBase
      • 🏀JavaScript
      • 🏀Android
      • 🏀JPA
      • 🏀Flutter
      • 🐸Utils
      • 🎫 Batch
      • 🎞️JenKins
      • 🎈Python
      • 🎗️AWS
      • 🦠Vue
      • 🐳React
      • 🖲️kafka
      • Next.js

공지사항

  • 공지사항

인기 글

태그

  • D

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
조각남자
[스프링 -4]Spring 파일 업로드 하기 (fileupload)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.