Sta*_*kJP 10 rest spring postman
我的控制器如下所示:
@RestController
@RequestMapping(path = RestPath.CHALLENGE)
public class ChallengeController {
private final ChallengeService<Challenge> service;
@Autowired
public ChallengeController(ChallengeService service) {
this.service = service;
}
@ApiOperation(value = "Creates a new challenge in the system")
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE},
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ChallengeDto create(@ApiParam(value = "The details of the challenge to create") @RequestPart("challengeCreate") @Valid @NotNull @NotBlank ChallengeCreateDto challengeCreate,
@ApiParam(value = "The challenge file") @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return service.create(challengeCreate, file);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试更改“消耗”以将APPLICATION_OCTET_STREAM_VALUE删除为MULTIPART_FORM_DATA_VALUE,并且还尝试将其删除,但是这些都无济于事。
如果您需要更多信息,请告诉我。谢谢。
Irf*_*sim 37
@Rokin 答案很好,但不需要将 json 放在文件中并上传。您也可以通过将内容类型传递给 json 对象来实现。邮递员在发送表单数据时支持内容类型选项。进一步参见下面的自我描述图像。
Rok*_*jan 17
对于 Spring 的 @RequestPart 使用 json 对象,在 Postman 中 - 您需要将 json 对象作为File而不是Text 发送。
将ChallengeCreateDto的内容放在一个 json 文件中,并保存为challenge.json。然后在 Postman 中上传这个文件,类型为File。我附上了一张 Postman 中的请求的截图,只是为了让它更清晰。
您还可以在较新版本的 Spring 中使用 @PostMapping 而不是 @RequestMapping,如下所示
@ResponseStatus(HttpStatus.CREATED)
@PostMapping()
public ChallengeDto create(@RequestPart("challengeCreate") ChallengeCreateDto challengeCreate,
@RequestPart("file") MultipartFile file) {
return service.create(challengeCreate, file);
}
Run Code Online (Sandbox Code Playgroud)
使用@RequestParam来获取字符串和文件将解决这个问题。在 Postman 中,使用 Content-Type 作为“multipart/form-data”,并在 Body 中将您的输入定义为表单数据。
例子:
@PostMapping(consumes = {"multipart/form-data"})
public Output send(@RequestParam String input, @RequestParam MultipartFile file) {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9948 次 |
| 最近记录: |