gnusraun

Egov 파일 업로드/다운로드 본문

Backend/Egov

Egov 파일 업로드/다운로드

gnusraun 2023. 5. 17. 14:10
728x90

Egov프레임워크에서 파일 업로드 및 다운로드하기

 

 

:: pom.xml

<!-- file upload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

<!-- MultipartHttpServletRequset -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

 

 

:: context-common.xml

multipartResolver 빈 추가

<!-- 파일 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="100000000" /> 
    <property name="maxInMemorySize" value="100000000" /> 
</bean>

 

 

:: context-properties.xml

properties.xml 을 이용하여 실제 파일 저장 경로를 추가

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

	<bean name="propertiesService" class="egovframework.rte.fdl.property.impl.EgovPropertyServiceImpl" destroy-method="destroy">
		<property name="properties">
	        <map>
	        	<entry key="pageUnit" value="10"/>
	        	<entry key="pageSize" value="10"/>
	        	<entry key="filePath" value="C:\\temp\\"/>	// 실제 저장 경로 추가
	        </map>
		</property>
	</bean>
	
</beans>

 

 

:: FileVO.java

file을 담을 VO 객체 추가

public class FileVO {
	
	private String fileName;
	private MultipartFile uploadFile;	// 파일 정보
	
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public MultipartFile getUploadFile() {
		return uploadFile;
	}
	public void setUploadFile(MultipartFile uploadFile) {
		this.uploadFile = uploadFile;
	}
	
}

 

 

:: FileUpload.jsp

encType="multipart/form-data"와 상단 VO객체와 매핑할 input 태그 name="uploadFile" 로 지정

<form id="formAction" action="/insertFile.do" method="post" encType="multipart/form-data">
	<input type="file" name="uploadFile">
</form>

 

 

:: FileController.java

properties에 지정한 경로를 사용하여 파일 업로드

// properties에서 지정한 경로
@Resource(name = "propertiesService")
EgovPropertyService propertiesService;

@RequestMapping(value = "/insertFile.do")
public String insertFile(FileVO fileVO) throws Exception {

    // 파일 업로드 처리
    String fileName = null;
    MultipartFile uploadFile = fileVO.getUploadFile();
    if (uploadFile != '' && !uploadFile.isEmpty()) {
        String basePath = propertiesService.getString("filePath");	// 경로 가져오기
        String originalFileName = uploadFile.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFileName); // 확장자 구하기
        String uuid = UUID.randomUUID().toString(); // UUID toString으로 문자 호출
        fileName = uuid + "." + ext;
        uploadFile.transferTo(new File(basePath + fileName));
    }

    // TODO 파일 데이터를 가공해서 DB 저장하기

    return "redirect:selectList.do";
}

 

 

:: FileDownloadController.java

파일명, 파일경로 지정 후 파일 다운로드

package egovframework.example.ivory.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class FileDownloadController {
 
    @Resource(name = "propertiesService")
	EgovPropertyService propertiesService;
    
    @RequestMapping(value = "/fileDownload.do")
    public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
 
        String filename = request.getParameter("fileName");
        String realFilename = "";
        System.out.println(filename);
 
        try {
            String browser = request.getHeader("User-Agent");
            // 파일 인코딩하지 않을 경우 에러 발생
            if (browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")) {
                filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
            } else {
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            } 
        } catch (UnsupportedEncodingException e) {
             System.out.println("UnsupportedEncodingException 발생");
        }
 
        // 파일 경로
        String basePath = propertiesService.getString("filePath");
        realFilename = basePath + filename;
        System.out.println(realFilename);
 
        File file = new File(realFilename);
        if (!file.exists()) {
            return;
        }
 
        // 파일명 지정
        response.setContentType("application/octer-stream");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
 
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(realFilename);
 
            int cnt = 0;
            byte[] bytes = new byte[512];
 
            while ((cnt = fis.read(bytes)) != -1) {
                os.write(bytes, 0, cnt);
            }
 
            fis.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
}

 

 

:: FileDownload.jsp

<h1>다운로드</h1>
<a href="/fileDownload.do?fileName=파일이름">

 

 

a태그 Group 26.png 클릭시 파일 다운로드 완료

 

 

출처 - https://ivory-room.tistory.com/64

728x90