티스토리 뷰

Java/Spring Boot

Spring boot 파일 업로드

CU SONAR 2019. 5. 16. 10:15

안녕하세요, 간만에 기술 글을 올리게 되네요.

 

다사다난했던 관계로 짬도 안났고, 게으르기도 했구요.

다시 한번 예전으로 돌아가 글을 열심히 써봐야겠어요^^

 

오늘은 Spring boot에서 파일 업로드하는 것에 대해서 알아보겠어요.

 

프로젝트 생성시 Dependency는 Web, Devtools, Lombok 3개만 추가를 합니다.

추가적으로 파일 처리를 위해 Apache commons-io를 추가하겠습니다.

 

build.gradle
plugins {
	id 'org.springframework.boot' version '2.1.5.RELEASE'
	id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.cusonar'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	
	// https://mvnrepository.com/artifact/commons-io/commons-io
	implementation 'commons-io:commons-io:2.6'
	
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'org.springframework.boot:spring-boot-devtools'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

 

FileController.java
package com.cusonar.hello.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/files")
@Slf4j
public class FileController {
	
	@Value("${temp.path}") private String tempPath;
	
	@PostMapping("")
	public String upload(@RequestParam String msg, @RequestParam MultipartFile[] files) throws IOException {
		log.info("Upload start : {}", msg);
		for (MultipartFile file : files) {
			File tmp = new File(tempPath + UUID.randomUUID().toString());
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), tmp);
			} catch (IOException e) {
				log.error("Error while copying.", e);
				throw e;
			}
		}
		return "success";
	}
}

 

application.yml 에 temp.path 를 설정해줍시다.

 

그리고 가동.

 

테스트는 

cURL
curl -v -H "Content-Type: multipart/form-data" -X POST -F "files=@test.pdf,test.txt" http://localhost:8080/files

 

Javascript with jQuery ajax
<!DOCTYPE html>
<html>
<head>
	<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
	<script>
		function submit() {
			var formData = new FormData();
			formData.append('msg', $('#msg').val());
			var files = $('#files')[0].files;
			for (var i = 0; i < files.length; ++i) {
				console.log(files[i]);
				formData.append('files', files[i]);
			}
			$.ajax({
				url: 'http://localhost:8080/files',
				method: 'POST',
				processData: false,
				contentType: false,
				data: formData,
				success: function(d) {
					console.log(d);
				}
			});
		}
	</script>
</head>
	
<body>
	Msg: <input id="msg" type="text">
	<input id="files" type="file" multiple>
	<button onclick="submit()">Submit</button>
</body>
</html>

위와 같이 비동기로 처리하셔도 되고, html form을 이용해서 넘기셔도 됩니다.

 

용량제한에 걸릴 경우는 아래와 같이 설정 변경해주시면 됩니다.

spring:
  servlet:
    multipart:
      max-file-size: -1 # default 1MB
      max-request-size: -1 # default 10MB

 

오늘은 간단하게 여기까지^^

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함