What's the practical difference between @RequestParam and @RequestPart for multipart file in spring controller?
Asked Answered
E

1

6

The Spring doc states @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part

  1. Now, what would be the practical differences between the two, in case all configurations are left to default
  2. What difference does it make, in case I upload a JSON/XML file and use @RequestParam or @RequestPart?
Etheline answered 28/8, 2022 at 18:45 Comment(0)
A
1

@RequestParam:

  • Best for straightforward form data submissions, where you are uploading files along with other simple form fields. (e.g., String, int).

  • Converts simple name-value pairs to method arguments. Relies on type conversion via a registered Converter or PropertyEditor.

  • @RequestParam expects simple strings or form-encoded data. It won't properly parse or convert complex JSON structures into Java objects. We need to write our custom logics for them

     @PostMapping("/upload2")
     public ResponseEntity<String> submitData(
          @RequestParam("file") MultipartFile file,
          @RequestParam("metadata") String metadata) {
      try {
          // Convert JSON string to MyObject
          ObjectMapper objectMapper = new ObjectMapper();
          Metadata myObject = objectMapper.readValue(metadata, Metadata.class);
    
          // Use the parsed object
          System.out.println("Key1: " + myObject.getKey1());
          System.out.println("Key2: " + myObject.getKey2());
    
          return ResponseEntity.ok("Data received");
      } catch (Exception e) {
          e.printStackTrace();
          return ResponseEntity.badRequest().body("Error processing data");
      }
    

@RequestPart:

  • When your request includes complex parts, such as a file along with a JSON payload that needs to be parsed separately. (e.g., JSON data).

  • Handles more complex content, like JSON or XML. Uses HttpMessageConverters to convert the request part based on the Content-Type. This can map JSON to Java objects in non-multipart requests.

    @PostMapping(path = "/upload1", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadComplex(
           @RequestPart("file") MultipartFile file,
          @RequestPart("metadata") Metadata metadata) {
      // Use the parsed Metadata object
      System.out.println("Key1: " + metadata.getKey1());
      System.out.println("Key2: " + metadata.getKey2());
    
      return ResponseEntity.ok("File and metadata uploaded");
     }
    }
    

sample postman request

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestPart.html

Atoll answered 2/8, 2024 at 15:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.