Issue
I'm trying to do a simple file upload via a Rest API created with Spring Boot and Kotlin. This is my code:
@RestController
@RequestMapping("/api")
class Controller {
@PostMapping("/upload")
fun handleFileUpload(@RequestParam("file") file: MultipartFile): ResponseEntity<String> {
try {
file.transferTo(File("C:\\upload\\" + file.originalFilename))
}
catch (e: Exception) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build()
}
return ResponseEntity.ok("File uploaded successfully.")
}
}
When I use Postman to test it, I get the status "400 Bad Request".
I'm using a Post-Request with the URL http://localhost:8080/api/upload. In the Header Section I left everything how it is (I read somewhere that the Content-Type Header sometimes causes trouble and therefore turned it off temporarily but this didn't help). In the Body section I chose "form-data", added a key called "file" and selected my test-file as a value.
What am I doing wrong?
Solution
Try to check your configuration, in particular if you have in the application.yml or application.properties the following:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}
And also in your pom.xml or build.gradle the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.1</version>
</dependency>
You can get some inspiration from this tutorial: https://www.baeldung.com/spring-file-upload
Answered By - cdr89
Answer Checked By - Robin (JavaFixing Admin)