본문 바로가기

Archived(Programming)/Spring #2(기초)

Static file 처리와 FileUpload

# Static Web Resource 처리

서버의 처리가 필요없는 Static Web resources는 요청 시 서버를 거치지 않고 곧바로 응답이 필요

특정 URL로 요청이 오면 static resource로 인식하고 바로 응답 수행

<mvc:resources mapping= "/resources/**" location="/WEB-INF/resources/" />

mapping: HTTP 요청 URL
location: 실제 응답할 파일이 있는 위치

ex) http://localhost:8080/hello/resources/scripts/jQuery.js

응답: /WEB-INF/resources/script/jQuery.js

 

# 파일 업로드 시 HTML 파일

<form method="post enctype="multipart/form-data"
...
</form>

멀티파트 지원 기능을 사용하기 위해 MultipartResolver를 스프링 설정으로 등록

maxUploadSize, maxInMemory 등 옵션 지정

common-fileupload 라이브러리

@Requestparam("file") MultipartFile file // 원본 Parameter로 가져오기

 

MultipartFile의 주요 메소드

Command 객체로 받아오기 > private MultipartFile file 이라는 property 설정 시 받아올 수 있음

파일 저장 시 보안을 위해 난수화 시켜서 저장하는 것이 중요

String fileRandomName = UUID.randomUUID().toString();

# 실습 1. Static File 처리

Controller에 Home 추가

package kr.co.acomp.hello.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import kr.co.acomp.hello.service.BbsService;
import kr.co.acomp.hello.vo.Article;

@Controller
@RequestMapping("/bbs") 
public class BbsController {

	@Autowired 
	private BbsService bbsService;
	
	@RequestMapping("")
	public String index() {
		return "home";
	}
	...
}

home.jsp View 내용 변경

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
	<link rel="stylesheet" href="/acomp/resources/styles/style.css">
</head>
<body>
<h1>
	Hello world!  
</h1>

	<h1>Spring Index Page</h1>
	<img alt="스프링 이미지" src="/acomp/resources/images/spring.png"> 
</body>
</html>

static 파일 처리를 위한 servlet-context.xml 추가

...
<resources mapping="/resources/**" location="/resources" />

style.css 파일생성 - hello-web/src/main/webapp/resources/styles 

body{
	background-color:yellow;
}

spring.png 이미지 붙여넣기- hello-web/src/main/webapp/resources/images

정상 작동

# 실습 2. FileUpload 처리

servlet-context.xml에 bean 추가

	...
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="maxUploadSize" value="104857600" />
		<beans:property name="defaultEncoding" value="UTF-8" />
	</beans:bean>

mvn respository 추가

...
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.4</version>
</dependency>

FileUploadController 생성

package kr.co.acomp.hello.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/bbs")
public class FileUploadController {
	
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public String upload(@RequestParam("file") MultipartFile file,
							@RequestParam("name") String fileName,
							Model model) throws IllegalStateException, IOException {
		
		if (!file.isEmpty()) {
			File f = new File("c:\\upload", file.getOriginalFilename());
			file.transferTo(f);
		}
		model.addAttribute("fileName", fileName);
		return "upload_ok";
	}
}

 

'Archived(Programming) > Spring #2(기초)' 카테고리의 다른 글

Spring Data Access 기술과 DataSource  (0) 2020.03.13
JUnit4 & Spring Test  (0) 2020.03.13
Restful API  (0) 2020.03.12
Http 파라미터 처리  (0) 2020.03.12
@Controller  (0) 2020.03.11