Spring Boot multipart file upload server

Upasana | September 11, 2020 | 2 min read | 266 views


In this tutorial we will develop simple spring boot 2.2 + Junit 5 + Kotlin based multi-part file upload server, and write mvc testcase for its validation.

You can download the source code for this project from Github location:

Gradle setup

build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
	id("org.springframework.boot") version "2.2.1.RELEASE"
	id("io.spring.dependency-management") version "1.0.8.RELEASE"
	kotlin("jvm") version "1.3.60"
	kotlin("plugin.spring") version "1.3.60"
}

group = "com.shunya"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

repositories {
	mavenCentral()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
	testImplementation("org.springframework.boot:spring-boot-starter-test") {
		exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
	}
}

tasks.withType<Test> {
	useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
	kotlinOptions {
		freeCompilerArgs = listOf("-Xjsr305=strict")
		jvmTarget = "11"
	}
}

Bootstrap App

Every Spring Boot app has an entry point that bootstraps the server, we will be using the below App.kt class that will start the Spring Container inside an embedded tomcat server.

App.kt
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class App

fun main(args: Array<String>) {
	runApplication<App>(*args)
}

Fileupload Controller

The following controller will accept a multi-part file and just print the content of file for demonstration purpose.

import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.BufferedReader

@RestController
class FileUploadController {

    val logger = LoggerFactory.getLogger(FileUploadController::class.java)

    @PostMapping("/fileupload")
    fun handleFileUpload(@RequestParam("file") file: MultipartFile): ServiceResponse {
        logger.info("handling fileupload for {}", file.name)
        val content = file.inputStream.bufferedReader().use(BufferedReader::readText)
        logger.info("file content = {}", content)
        return ServiceResponse.ok(content)
    }
}

data class ServiceResponse(val isSuccess: Boolean,
                           val data: String? = null) {

    companion object {
        fun ok(data: String): ServiceResponse {
            return ServiceResponse(isSuccess = true, data = data)
        }

        fun fail(): ServiceResponse {
            return ServiceResponse(isSuccess = false)
        }
    }
}

Configuration

We can configure file uplaod attributes like max upload size, request size etc. using Spring Boot properties file.

application.properties
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=1MB

Running the application

We can start the server using the below gradle command from terminal.

$ ./gradlew :bootRun

Top articles in this category:
  1. Spring Webclient multipart file upload
  2. Multipart file upload with RestTemplate
  3. S3 File upload & download with AWS Java SDK v2
  4. Setting a Random Port in Spring Boot Application at startup
  5. Run method on Spring Boot startup
  6. Download a file using Spring RestTemplate
  7. Running Spring Boot app as a service in unix

Recommended books for interview preparation:

Find more on this topic: