Last active
January 27, 2025 13:56
-
-
Save benoitdevos/fc49f3b9633eb7ba0f5c8dfe085cba14 to your computer and use it in GitHub Desktop.
Adding support for application/octet-stream in RestController (Spring Boot) - java version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mycompany.myappp.config; | |
import org.apache.commons.io.IOUtils; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.http.HttpInputMessage; | |
import org.springframework.http.HttpOutputMessage; | |
import org.springframework.http.MediaType; | |
import org.springframework.http.converter.AbstractHttpMessageConverter; | |
import org.springframework.http.converter.HttpMessageConverter; | |
import org.springframework.http.converter.HttpMessageNotReadableException; | |
import org.springframework.http.converter.HttpMessageNotWritableException; | |
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.List; | |
/** | |
* Configure Spring Boot to allow upload of octet-stream. | |
*/ | |
@Configuration | |
public class WebConfig extends WebMvcConfigurationSupport { | |
@Override | |
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { | |
converters.add(new AbstractHttpMessageConverter<InputStream>(MediaType.APPLICATION_OCTET_STREAM) { | |
protected boolean supports(Class<?> clazz) { | |
return InputStream.class.isAssignableFrom(clazz); | |
} | |
protected InputStream readInternal(Class<? extends InputStream> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { | |
return inputMessage.getBody(); | |
} | |
protected void writeInternal(InputStream inputStream, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { | |
IOUtils.copy(inputStream, outputMessage.getBody()); | |
} | |
}); | |
super.configureMessageConverters(converters); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for an idea of how it works!
This implementation removes default convertors (for example, Jakson's for
application/json
). To save default convertors, add this line before callsuper.configureMessageConverters(converters);
on line 39.