Spring Boot multi-part file upload

Carvia Tech | July 22, 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. Multipartfile upload in RestTemplate using ByteArrayResource & FileSystemResource
  2. AWS SDK 2.0 - S3 File upload & download in Java
  3. SendGrid emails in Spring Boot
  4. Sendgrid Dynamic Templates with Spring Boot
  5. Custom banner in spring boot
  6. SendGrid Attachments with Spring Boot
  7. Basic Auth Security in Spring Boot 2


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info