I am making a REST API in Java spring. I want to make a post request in postman and upload some text and a pdf file to my postgreSQL database. The connection works. I tested it with another endpoint. I tried alot of things but none of them works.
I heard you can do this with postman - Form data.
What I tried: added this to the @PostMapping() --> No success
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
In postman:
added Content-type : application/json
andContent-type : multipart/form-data
Both of them with no success :(...
Below my restcontroller
@RestController
public class SheetMusicController {
@Autowired
SheetMusicRepository sheetMusicRepository;
@GetMapping("/sheetmusic")
public List<SheetMusic> index(){
return sheetMusicRepository.findAll();
}
@PostMapping(value = "/sheetmusic")
public SheetMusic create(@RequestBody Map<String,String> body){
String title = body.get("title");
byte[] pdf = "".getBytes();
SheetMusic sheetMusic = new SheetMusic(title,"","","",pdf);
return sheetMusic;
}
}
And a picture of postman Postman
I don't see what I do wrong. I hope you guys can help me out!
Greetings,
You should implement a multipart form-data
request:
First, you need to add to maven:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
Second, you need to add this Bean
configuration:
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
Finally, your Post
method should be like this:
@PostMapping(value = "/sheetmusic")
public SheetMusic create(@RequestParam("file") MultipartFile file, @RequestParam("title") String title) {
// Your business
}
NOTE: for the Postman
you just need to select the body type form-data
and the Content-Type will be set automatically.