简体   繁体   中英

Spring Converters for @RequestParam

I want to have InputStream of form field in my Controller, wheter @RequestParam is String or MultipartFile. Do anyone know how to properly register converter. What i want achive looks like this

@RequestMapping(value = "/test", method = RequestMethod.POST)
void sendData(@RequestParam("data") InputStream){
   // Deal with InputStream
}

I have written two converters, but i'm not sure how to register them in spring boot and force them to work:

public class StringToStreamConverter implements Converter<String, InputStream> {

   @Override
   public InputStream convert(String source) {
     return new ByteArrayInputStream(source.getBytes());
   }
}


public class MultipartFileToStreamConverter 
   implements Converter<MultipartFile, InputStream> {

   @Override
   public InputStream convert(MultipartFile source) {
     return source.getInputStream();
   }
}

I have found somepart solution.

If config class extends WebMvcConfigurationSupport i can override method public FormattingConversionService mvcConversionService() where i can add my converters and it just works.

@Configuration
public class TestConfig extends WebMvcConfigurationSupport {
   @Override
   public FormattingConversionService mvcConversionService() {
       FormattingConversionService f = super.mvcConversionService();
       f.addConverter(new StringToStreamConverter());
       f.addConverter(new MultipartFileToStreamConverter());
       return f;
   }
}

I wonder if anyone has better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM