본문 바로가기
STUDY/SPRING

스프링(3.0) 파일 업로드·다운로드

by Anne of Green Galbes 2019. 4. 19.

파일 업로드


1. 라이브러리 다운

① FileUpload

○ pom.xml

<!-- commons-fileupload -->

<dependency>

  <groupId>commons-fileupload</groupId>

  <artifactId>commons-fileupload</artifactId>

  <version>1.3.3</version>

</dependency>


② IO

○ pom.xml

<!-- commons-io -->

<dependency>

  <groupId>commons-io</groupId>

  <artifactId>commons-io</artifactId>

  <version>2.6</version>

</dependency>


2. servlet-context.xml

○ 파란색 줄은 클래스 안에 있는 메고드로, 이름에 오타가 생기면 안된다

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<beans:property name="maxUploadSize" value="10240000"/>

<beans:property name="maxInMemorySize" value="1024000"/>

<beans:property name="defaultEncoding" value="UTF-8"/>

</beans:bean>


3. HomeController.java

@RequestMapping(value = "/upload.action", method = RequestMethod.POST)

public String upload(MultipartHttpServletRequest request, String str) throws Exception {

//request.getSession()는 생략가능

//이제는 WEB-INF밑에 저장하기 위해 뒤에 주소 변경

String path = request.getSession().getServletContext().getRealPath("/WEB-INF/files");

//파일의 이름 읽어옴

MultipartFile file = request.getFile("upload");

if(file!=null && file.getSize()>0) {

try {

FileOutputStream fos = new FileOutputStream(path+"/" + file.getOriginalFilename());

InputStream is = file.getInputStream();

byte buffer[] = new byte[512];

while(true) {

int data = is.read(buffer,0,buffer.length);

if(data==-1) {

break;

}

fos.write(buffer,0,data);

}

is.close();

fos.close();

} catch (Exception e) {

System.out.println(e.toString());

}

}

return "uploadResult";

}


4. 화면


파일 다운로드


1. HomeController.java

@RequestMapping(value = "/download.action", method = {RequestMethod.POST,RequestMethod.GET})

public ModelAndView download() throws Exception {

ModelAndView mav = new ModelAndView();

mav.setView(new DownloadView());

return mav;

}


2. DownloadView,java

○ 다운로드 처리 순서

① 브라우저에게 처리할 수 없는 컨테츠라고 알려준다.

   → 브라우저가 처리할 수 없어 다운로드를 실행

   - 둘 중 하나를 사용

      response.setContentType("application/octet-stream");

      response.setContentType("application/unknown");

② 다운로드 처리할 때 필요한 정보를 제공한다

③ 파일 응답 스트림에 기록한다

④ 파일 다운로드를 실행한다

public class DownloadView extends AbstractView{


@Override

protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,

HttpServletResponse response) throws Exception {


//1

response.setContentType("application/unknown");

//2

//수동으로 파일 이름 작성

response.addHeader("Content-Disposition","Attachment;FileName=\"2017-06-02 17-32-45.jpg\"");

//3

String file = request.getSession().getServletContext().getRealPath("/WEB-INF/files/2017-06-02 17-32-45.jpg");

//4

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

while(true) {

int data = bis.read();

if(data!=-1)

bos.write(data);

else

break;

}

bis.close();

bos.close();

}

}

'STUDY > SPRING' 카테고리의 다른 글

스프링(3.0) Spring Web View  (0) 2019.04.19
스프링(3.0) 게시판 스프링 JDBC로 변경  (0) 2019.04.18
스프링(3.0) MVC : 게시판 만들기  (0) 2019.04.18
스프링(3.0) Spring AOP  (0) 2019.04.17
스프링(3.0) MyBatis 연결  (0) 2019.04.17

댓글