[英]Rest API java spring - Upload text and pdf to PostgreSQL database (postman - form data)
I am making a REST API in Java spring.我正在 Java spring 中制作一个 REST API。 I want to make a post request in postman and upload some text and a pdf file to my postgreSQL database.
我想在邮递员中发出帖子请求并将一些文本和 pdf 文件上传到我的 postgreSQL 数据库。 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我尝试过的:将此添加到@PostMapping() --> 没有成功
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
In postman: added Content-type : application/json
and Content-type : multipart/form-data
在邮递员中:添加了
Content-type : application/json
和Content-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,你好,
Change @Postmapping to @Requestmapping.将@Postmapping 更改为@Requestmapping。 It should work then.
它应该工作。
You should implement a multipart form-data
request:你应该实现一个
multipart form-data
请求:
First , you need to add to maven:首先,您需要添加到 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
配置:
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
Finally , your Post
method should be like this:最后,你的
Post
方法应该是这样的:
@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.注意:对于
Postman
您只需要选择 body 类型form-data
并且 Content-Type 将自动设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.