jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

Spring

[Spring] Day 15 파일 업로드 (Code)

2022. 4. 9. 23:55

1. pom.xml에 추가 

<!-- 파일 업로드 관련 -->
		<!-- I/O : 입출력 관련 : https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.4</version>
		</dependency>

 

2. servlet-context에 추가

<!-- 파일 업로드를 위한 설정 
	maxUploadSize: 파일 업로드 크기 : -1은 제한 없음-->
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="maxUploadSize" value="-1"/>
		<beans:property name="defaultEncoding" value="UTF-8"/>
	</beans:bean>

 

3. UploadController

package com.board.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/upload/")
public class UploadController {

	@GetMapping("uploadForm")
	public void uploadForm() {
		System.out.println("upload form 요청");
	}
	
	@PostMapping("uploadPro")
	public String uploadPro(String msg, MultipartHttpServletRequest request, Model model) { 
		//이미지가 넘어오긴 넘어오는데 바로 끄집어낼 수 없음. MultipartHttpServletRequest로 리퀘스트 객체 꺼내기
		
		//1. 넘어온 파일 정보 꺼내기
		System.out.println("!!msg: " +msg);
		MultipartFile mf=  request.getFile("img"); //form에서 보내준 이름으로 꺼내줌
		System.out.println("!!mf size: " + mf.getSize());
		System.out.println("!!mf original name: " + mf.getOriginalFilename());
		System.out.println("!!mf content type: " + mf.getContentType());
		
		String ct = mf.getContentType();
		String type = ct.substring(0, ct.indexOf("/")); //타입에 /plain 앞까지 잘려서 담김
		if (!type.equals("image")) { //이미지가 아니면 저장하지 말자
			System.out.println("이미지 파일만 저장해주세요.");
			return "redirect:/upload/uploadForm"; //저장하지말고 폼페이지로 강제 이동 
		} 
		
		
		//서버에 파일 저장
		//2. 파일 저장할 폴더 경로 찾기 (save)
		String savePath = request.getRealPath("resources\\save");
		System.out.println("!!savePath: " + savePath);
		
		/*
		//3. 파일 이름 (원본 파일 이름?을 저장할 것인가..no, 파일 이름 중복 안되게 처리해서 서버에 저장)
		//3-1. 오리지날 파일 명+ 현재 시간 millisecond + 확장자명 
		String orgName = mf.getOriginalFilename();
		String ext = orgName.substring(orgName.lastIndexOf(".")); //substring 인자의 위치부터 뒤를 잘라줌. lastindexof: .의 위치를 찾음.
		String imgName = orgName.substring(0, orgName.lastIndexOf(".")); //처음부터 . 전까지 잘라줌
		System.out.println("!! ext: " + ext);
		System.out.println("!! imgName: " + imgName);
		String newName = imgName + System.currentTimeMillis() + ext;
		System.out.println("!! newName: " + newName);
		*/
		//3-2 UUID로 바꿔주기/ UUID + orgName
		String orgName = mf.getOriginalFilename();
		UUID uuid = UUID.randomUUID();
		String newName = uuid + orgName;
		
		
		
		//4. 파일을 실제로 저장 처리 
		//: 내가 만든 파일명과 폴더 전체 경로를 연결해서 그쪽으로 파일을 이동해주는 개념
		String imgPath = savePath + "\\" + newName;
		File f =new File(imgPath); //이 경로 안에 이 이름으로 파일 객체 만들어.. 
		try {
			mf.transferTo(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//5. 디비에 파일 이름 저장: savePath 빼고 newName만 저장하는게 효율적임. 
		
		
		//view에 파일명 전달해서 pro 페이지에 img로 띄우기 
		//(사용자가 브라우저에서 내가 업로드한 이미지 보기)
		model.addAttribute("imgName",newName);
		
		return "upload/uploadPro";
	}
	
	//다운로드 버튼 보여지는 페이지 요청
	@GetMapping("downForm")
	public void downForm() {
		System.out.println("다운로드 버튼 페이지 요청");
	}
	
	//다운로드 버튼 눌렸을때 요청 처리
	@RequestMapping("download")
	public ModelAndView down(HttpServletRequest request) {
		//버튼 사용자가 누르면 다운시켜줄 파일 객체 생성
		String path = request.getRealPath("resources\\imgs");
		System.out.println(path);
		String filePath = path + "\\profileImage.png";
		File f = new File (filePath);
		//fileDown: viewName에 해당하는 값 -> servlet-context.xml에 DownloadView클래스 빈으로 등록한 id와 일치
		//downloadFile: Model로 보내는 데이터의 이름 -> DownloadView 클래스 안에 File file = (File)model.get("downladFile"); 키값과 일치
		//f: 다운시킬 실제 File 객체: Model로 보내는 실제 데이터
		ModelAndView mv = new ModelAndView("fileDown", "downloadFile", f);
		//								model.addAttribute("download",f)
		return mv;
	}
	
	
	
}

 

uploadForm.jsp

<%@ 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>

<h2>upload form</h2>
   <form action="/upload/uploadPro" method="post" enctype="multipart/form-data">
      MSG : <input type="text" name="msg" /> <br/>
      File : <input type="file" name="img" /> <br/>
      <input type="submit" value="전송" />
   </form>

</body>
</html>

 

uploadPro.jsp

<%@ 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>
<h2>uploadPro</h2>
<img src="/resources/save/${imgName}" width="300">

</body>
</html>

 

DownloadAndView.java (service)

package com.board.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

//다운로드 처리 클래스
public class DownloadView extends AbstractView {
	
	public DownloadView() {
		setContentType("application/download; charset=utf-8"); 
	}

	@Override							
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {		
		
		File file = (File)model.get("downloadFile");		
		response.setContentType(getContentType()); 			
		response.setContentLength((int)file.length());		
		
		String fileName = java.net.URLEncoder.encode(file.getName(), "UTF-8"); 
		response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\";"); 
		response.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream out = response.getOutputStream();		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);		
			FileCopyUtils.copy(fis, out);			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(fis != null) { try {fis.close();}catch(Exception e2) { e2.printStackTrace(); } }
			out.flush();
		}
		
		
		
	}
	
}

 

downForm.jsp

<%@ 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>
<%@ include file = "uploadForm.jsp" %>

	<h2>다운을 받으시오</h2>
	<button onclick="window.location='/upload/download'">다운</button>

</body>
</html>
    'Spring' 카테고리의 다른 글
    • [SpringBoot]2022/05/19: thymeleaf, Single table CRUD
    • [SpringBoot]2022/05/18: JPA, Entity, 페이징, Querydsl
    • [Spring] Day15 파일 업로드 (Note)
    • [Spring] Day14 댓글 답글 달기 + 페이징 처리 (Code)

    티스토리툴바