2021.01.22 일지

83160 단어 SpringSpring

File Upload/Download

pom.xml

  • pom.xml에 하단 xml을 추가해준다.
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version> 
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.5</version>
		</dependency>

servlet-context.xml

  • servlet-context.xml에 하단 xml을 추가해준다.
<!-- servlet-context : 파일 업로드용 resolver -->
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="defaultEncoding" value="UTF-8" />
		<beans:property name="maxUploadSize" value="10485760" />
		<beans:property name="maxUploadSizePerFile" value="2097152"/>
		<beans:property name="maxInMemorySize" value="10485756"/>
	</beans:bean>

<!-- servlet-context : 파일 다운로드 -->
	<beans:bean id="fileDownloadView" class="soo.md.filesetting.FileDownloadView" />
	<beans:bean id="fileViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
	    <beans:property name="order" value="0" />
	</beans:bean>

controller

  • peachy.md.controllerFileController.java를 만들어준다.
package peachy.md.controller;

import java.io.File;
import java.util.ArrayList;

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.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import peachy.md.filesetting.Path;
import peachy.md.service.FileUploadService;

@Log4j
@Controller
@AllArgsConstructor
@RequestMapping("file")
public class FileController {
   private FileUploadService service; //Spring 4.3 ~: AutoInjection (with @AllArgsConstructor )
   
   @GetMapping("form.do")
   public String formFu() {
      return "file/form";
   }
   @PostMapping("upload.do")
   public String upload(@RequestParam String name, @RequestParam MultipartFile file) {
      log.info("#name: " + name + ", file: " + file);
      
      String ofname = file.getOriginalFilename();
      if(ofname != null) ofname = ofname.trim();
      if(ofname.length() != 0) {
         String url = service.saveStore(file);
      }
      
      return "redirect:list.do";
   }
   @GetMapping("list.do")
   public ModelAndView fileList() {
      File fStore = new File(Path.FILE_STORE);
      if(!fStore.exists()) fStore.mkdirs();
      File files[] = fStore.listFiles();
    
      return new ModelAndView("file/list", "files", files);
   }
   @GetMapping("del.do")
   public String del(@RequestParam String fname) {
      File file = new File(Path.FILE_STORE, fname);
      if(file.exists()) file.delete();
      
      return "redirect:list.do";
   }
   @GetMapping("form_mt.do")
   public String formFuMt() {
      return "file/form_mt";
   }
   @PostMapping("upload_mt.do")
   public String uploadMt(@RequestParam ArrayList<MultipartFile> files) {
      for(MultipartFile file: files) {
         String ofname = file.getOriginalFilename();
         if(ofname != null) ofname = ofname.trim();
         if(ofname.length() != 0) {
            String url = service.saveStore(file);
         }
      }
      
      return "redirect:list.do"; 
   }
   @GetMapping("download.do")
   public ModelAndView download(@RequestParam String fname) {
      File file = new File(Path.FILE_STORE, fname);
      if(file.exists()) {
         return new ModelAndView("fileDownloadView", "downloadFile", file);
      }else {
         return new ModelAndView("redirect:list.do");
      }
   }
}
  • peachy.md.filesettingFileDownloadView.java 생성해준다.
package peachy.md.filesetting;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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;

import lombok.extern.log4j.Log4j;

@Log4j
public class FileDownloadView extends AbstractView { // View역할을 하는 JSP같은 것이다.
   public FileDownloadView() {
      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 value = "attachment; filename="+ java.net.URLEncoder.encode(file.getName(), "utf-8") +";";
      response.setHeader("Content-Disposition", value);
       response.setHeader("Content-Transfer-Encoding", "binary");
       
       OutputStream os = response.getOutputStream();
       FileInputStream fis = null;
       try {
          fis = new FileInputStream(file);
          FileCopyUtils.copy(fis, os);
          
          os.flush();
       }catch(IOException ie) {
          log.info("FileDownloadView ie: " + ie);
       }finally {
          if(fis != null) fis.close();
          if(os != null) os.close();
       }
   }
}
  • peachy.md.filesettingPath.java 생성해준다.
package peachy.md.filesetting;

public class Path {
	public static final String FILE_STORE = "C:/spring/tmp/";
}
  • peachy.md.service에서 FileUploadService.java를 만들어준다.
package peachy.md.service;

import org.springframework.web.multipart.MultipartFile;

public interface FileUploadService {
   String saveStore(MultipartFile file);
   boolean writeFile(MultipartFile file, String saveFileName);
}
  • peachy.md.service에서 FileUploadServiceImpl.java를 만들어준다.
package peachy.md.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.log4j.Log4j;
import peachy.md.filesetting.Path;

@Log4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

   @Override
   public String saveStore(MultipartFile file) {
      String ofname = file.getOriginalFilename();
      int idx = ofname.lastIndexOf(".");
      String ofheader = ofname.substring(0, idx);
      String ext = ofname.substring(idx);
      long ms = System.currentTimeMillis();
      StringBuilder sb = new StringBuilder();
      sb.append(ofheader);
      sb.append("_");
      sb.append(ms);
      sb.append(ext);
      String saveFileName = sb.toString();
      
      long fsize = file.getSize();
      log.info("#ofname: " + ofname + ", saveFileName: " + saveFileName + ", fsize: "+fsize);
      
      boolean flag = writeFile(file, saveFileName);
      if(flag) {
         log.info("#업로드 성공");
      }else {
         log.info("#업로드 실패");
      }
      return Path.FILE_STORE + saveFileName;
   }

   @Override
   public boolean writeFile(MultipartFile file, String saveFileName) {
      File rDir = new File(Path.FILE_STORE);
      if(!rDir.exists()) rDir.mkdirs();
      
      FileOutputStream fos = null;
      try {
         byte data[] = file.getBytes();
         fos = new FileOutputStream(Path.FILE_STORE+saveFileName);
         fos.write(data);
         fos.flush();
         
         return true;
      }catch(IOException ie) {
         return false;
      }finally {
         try {
            if(fos != null) fos.close();
         }catch(IOException ie) {}
      }
   }
}

jsp

  • views/file 페이지에 추가해줄 jsp들이다.

form_mt.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Fileupload Form Multi</title>
		<style>
			a{text-decoration:none}
		</style>
	</head>
	<body style="text-align:center">
		<h1>Fileupload Form Multi</h1>

		<form action="/file/upload_mt.do"  method="post" enctype="multipart/form-data">
		 <div>
		   <input type='file' name='files'>
		 </div>
		 <div>
		   <input type='file' name='files'>
		 </div>
		 <div>
		   <input type='file' name='files'>
		 </div>
		 <div>
		   <input type='file' name='files'>
		 </div>
		 <div>
		   <input type='file' name='files'>
		 </div>
		 <div>
		   <input type='submit'>
		 </div>   
		</form>

	</body>
</html>

form.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>File upload Form</title>
		<style>
			a{text-decoration:none}
		</style>
	</head>
	<body style="text-align:center">

		<h1>File upload Form</h1>
		<form action="/file/upload.do"  method="post" enctype="multipart/form-data">
					이름: <input name="name"><br/>
				파일: <input type='file' name='file'><br/>
			<input type='submit' value="전송">
		</form> 
		
	</body>
</html>

list.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>list.jsp</title>
		<style>
			a{text-decoration:none}
		    table{
		        width:50%
		    }
			table,th,td {
			  border : 1px solid black;
			  border-collapse: collapse;
			}
			th,td {
			  padding: 5px;
			}
		</style>
	</head>
	<body style="text-align:center">
	    <h1>FileUpload with Spring5</h1>
	    <a href="form.do">업로드 폼</a>
	    &nbsp;&nbsp;&nbsp;&nbsp;
	    <a href="form_mt.do">업로드 폼(멀티)</a>
	    &nbsp;&nbsp;&nbsp;&nbsp;
	    <a href="../">인덱스</a>
	    <br/><br/>
	    
	    <center>
	    <table>
	        <tr>
	           <th>이름</th>
	           <th>크기</th>
	           <th>삭제</th>
	        </tr>
			   <c:if test="${empty files}">	
	           <tr>
	              <td align="center" colspan="3">파일이 하나도 없음</td>
	           </tr>
               </c:if>
               <c:forEach items="${files}" var="file">
	           <tr>
	             <td align="center">
	               <a href="download.do?fname=${file.name}">${file.name}</a>
	             </td>
	             <td align="center">${file.length()}</td>
	             <td align="center">
	               <a href="del.do?fname=${file.name}">삭제</a>
	             </td>
	          </tr>
              </c:forEach>
	    </table>
	    </center>
	</body>
</html>

좋은 웹페이지 즐겨찾기