spring-bootspring-mvc

HttpMediaTypeNotSupportedException when uploading files using Spring boot


I am encountering an issue while trying to upload files using Spring WebFlux in my Kotlin application(using kotlin and spring boot). Despite properly configuring my controller to handle multipart file uploads, I am receiving an HttpMediaTypeNotSupportedException with the message Content-Type 'image/jpeg' is not supported.

Here is my setup:

1. Controller Implementation:

@RestController
@Validated
class S3Controller {
    private val logger = LoggerFactory.getLogger(S3Controller::class.java)

    @Autowired
    private lateinit var s3: S3Service

    companion object {
        const val UPLOAD_FILE = "/uploadFile"
    }

    @Value("\${minio.buckets.kyc-bucket-name}")
    private val portfoliosBucket: String = ""

    @PostMapping(UPLOAD_FILE, consumes = ["multipart/form-data", MediaType.ALL_VALUE])
    suspend fun uploadFile(@RequestPart("file") file: FilePart): ResponseEntity<String> {
        logger.info("Received file: ${file.filename()} for upload")
        return try {
            val fileName = file.filename()
            s3.upload(
                bucket = portfoliosBucket,
                fileName = fileName,
                folder = "portfolios",
                part = file
            )
            logger.info("File uploaded successfully: $fileName")
            ResponseEntity.ok("File uploaded successfully: $fileName")
        } catch (e: Exception) {
            logger.error("Failed to upload file: ${e.message}", e)
            ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: ${e.message}")
        }
    }

2. Application Configuration (application.yml):

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB

3. Error Message:

I get the following warning on the log:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'image/jpeg' is not supported]
  1. Why is my application rejecting the image/jpeg content type?
  2. What additional configurations should I check to ensure that file uploads are correctly processed?
  3. Are there any common pitfalls in setting up multipart file uploads with Spring WebFlux that I might be missing?

Solution

  • The issue I was encountering in my Spring Boot application was that I had both spring-web-mvc and spring-web-flux dependencies included in my build.gradle.kts file.It seems the two dependencies cannot be enabled together.To resolve this I modified my application properties file by adding the following line spring.main.web-application-type=reactive