코딩하는 문과생

[Spring] Spring 프레임워크(4) - static 파일처리, 파일 업로드 본문

웹 프로그래밍/Spring

[Spring] Spring 프레임워크(4) - static 파일처리, 파일 업로드

코딩하는 문과생 2020. 3. 8. 23:33

[Static Web Resource]

: 서버의 처리가 필요없는 자원들은 요청시 서버를 거치지 않고 곧바로 응답이 필요

 

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

mapping : url경로, location: 파일들이 있는 위치

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

 

[파일 업로드]

  • HTML: form태그 이용

  • Spring: MultipartResolver를 이용, dependency추가가 필요(common fileupload), MultipartFile이라는 객체가 파일을 받는다.

[MultipartFile]

  • MultipartFile의 주요 메소드: getName(), isEmpty(), getOriginalFileName()...
  • Command객체에 저장이 가능
  • randomUUID(): 파일명을 난수화시켜서 저장하는 것이 보안에 좋다.

 

ex. static처리

-servlet-context.xml

	<!-- 해당 url로 접근되면 dispatcher가 컨트롤러가 아닌 해당 파일을 찾는다. -->
	<mvc:resources location="/WEB-INF/resources/" mapping="/resources/**"/>

-BbsController

	@GetMapping("")
	public String index() {
		return "index";
	}

-index.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>
<link rel="stylesheet" href="/hello-web/resources/styles/style.css">
</head>
<body>
	<h1>Spring Index Page</h1>
	<img alt="스프링 이미지" src="/hello-web/resources/images/spring.png">
</body>
</html>

-style.css

body {
	background-color: cyan;
}

 

ex. 파일 업로드

- servlet-context.xml

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

- pom.xml: 의존성 추가

	<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
	<dependency>
	    <groupId>commons-fileupload</groupId>
	    <artifactId>commons-fileupload</artifactId>
	    <version>1.3.3</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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

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

	@PostMapping("/upload")
	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";
	}
}

결과