java - 如何一起使用@RequestBody和@RequestParam

标签 java spring spring-mvc spring-boot

我尝试使用 @RequestBody@RequestParam 通过 Postman 发送 JSON 和多个文件,但它不起作用。是否可以在 API 中同时使用这两种注释?

@RequestMapping(value = "/save/product/test", method = RequestMethod.POST)
public ResponseEntity<?> save(@Valid @RequestBody ProductVo productVo, @RequestParam("files") @NotNull @NotBlank MultipartFile[] uploadfiles) {

    System.out.println("body " + productVo.toString());
    for (MultipartFile file :  uploadfiles) {
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getContentType());
        System.out.println(file.getName());
        System.out.println(file.getSize());

    }
    return new ResponseEntity<APIResponse>(this.apiResponse, HttpStatus.NO_CONTENT);
}

最佳答案

@RequestParam 从 uri 获取参数,您实际上是在尝试实现其他目标。

这是一个示例 Controller ,采用 json 正文和多部分文件:

@RestController
@RequestMapping("/users")
public class UserController {

    UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping({"/", ""})
    public ResponseEntity<User> post(@RequestPart("request") UserCreateRequest request, @RequestPart("file") MultipartFile file) throws IOException {

        String photoPath = UUID.randomUUID() + file.getOriginalFilename().replaceAll(" ", "").trim();

        // other logic

        return ResponseEntity.ok(userService.create(request));
    }
}

关于java - 如何一起使用@RequestBody和@RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51917110/

相关文章:

Java 路径异常

java - 选择哪种数据结构?

java - Spring Batch 分区 + 线程

java - 无法写入 HTTP 消息 : org. springframework.http.converter.HttpMessageNotWritableException:

java - 解析Java格式的日期字符串[2012-07-15T20 :55:33+00:00]

java - Eclipse Google -App -Engine "Will NOT Enhance"

java - 如何以编程方式获取 DAO 的 PlatformTransactionManager?

java - Spring REST Api——访问存储库中的用户详细信息

java - "Link doesn' t work”添加基本的 Spring Security 支持后

java - 如何避免在我的java bean中使用Spring注释并仅在配置类中使用它们?