sanguk.dev
작성완료
Spring 파일 업로드

Spring 파일 업로드

Spring 파일 업로드를 위해 commons-io와 commons-fileupload 의존성을 추가하고, 파일을 처리하는 FileController를 생성하여 파일을 지정된 경로에 저장하는 방법을 설명합니다.

JavaSpringSpring Boot

Dependencies 추가

/pom.xml

xml
<dependencies>
	...
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.13.0</version>
	</dependency>
	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.5</version>
	</dependency>
	...
</dependencies>

Controller 생성

/src/main/java/com/group/project/controller/FileController.java

java
package com.sanguk.restapi.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

import org.springframework.web.bind.annotation.PostMapping;

@RestController
@RequestMapping("/api/file")
public class FileController {

  @PostMapping
  public boolean postFile(@RequestPart MultipartFile file) throws IllegalStateException, IOException {
    String fileName = file.getOriginalFilename();
    long fileSize = file.getSize();

    try {
      file.transferTo(new File("저장할 경로/" + fileName));
    } catch (IOException e) {
      System.out.println(e);
    }
    return true;
  }

}