How to pass body @RequestBody and @RequestParam in

2019-08-18 05:21发布

问题:

I'm trying to pass a body and a param in the same request using the package dio.

I have this method on Spring boot:

@PostMapping("/guardarproducto")
    public ResponseEntity<Usuario> insertProduct(@RequestBody String body, @RequestParam("imagen") MultipartFile imagen) {
 ....
}

I've tried to do this request with:

FormData formData = new FormData.from({
        "barcode": barcode != null ? this.barcode : null,
        "idUsuario": user.id,
        "nombre": _textController.text,
        "aditivos": aditivosLeidos,
        "imagen": pickedImage
      });
      await dio.post('https://10.0.2.2:8443/api/guardarproducto',
          data: formData);

But i get:

{
    "timestamp": "2019-07-03T12:11:39.902+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required request body is missing: public org.springframework.http.ResponseEntity<ual.dra.rest.Usuario> ual.dra.rest.AditivoController.insertProduct(java.lang.String,org.springframework.web.multipart.MultipartFile)",
    "path": "/api/guardarproducto"
}

How can i pass body and request param in the same request?

I don't care use Dio or Http package.

回答1:

Okay I am not sure how flutter and dart works, but in spring boot when you try to post both RequestBody and MultiPart consider using @RequestPart

@PostMapping("/guardarproducto")
public ResponseEntity<Usuario> insertProduct(@RequestPart("body") String body,
                                             @RequestPart("imagen") MultipartFile imagen) {
 ....
}

and also while posting a body in FormData, you have set the json in one object.Let say below is the json.

{
        "barcode": "XAWA"
        "idUsuario": 1,
        "nombre": 1,
        "aditivos": "1"
}

then in FormData

FormData formData = new FormData.from({
        "body" : {  "barcode": barcode != null ? this.barcode : null,
                   "idUsuario": user.id,
                  "nombre": _textController.text,
                  "aditivos": aditivosLeidos
                 } 
        "imagen": pickedImage
      });

Note : "body" and "imagen" are in same level.


回答2:

Use @RequestPart for both the request body and multipart parameter.