I have the following image download method in my controller (Spring 4.1):
@RequestMapping(value = \"/get/image/{id}/{fileName}\", method=RequestMethod.GET)
p
Pay attention to your HTTP Accept header. For example, if your controller produces "application/octet-stream" (in response), your Accept header should NOT be "application/json" (in request):
@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void download(HttpServletResponse response) {}
You need to decide how the media type of the response should be determined by Spring. That can be done in several ways:
By default, Spring looks at the extension rather than the Accept
header. This behaviour can be changed if you implement a @Configuration
class that extends WebMvcConfigurerAdapter (or since Spring 5.0 simply implement WebMvcConfigurer. There you can override configureContentNegotiation(ContentNegotiationConfigurer configurer) and configure the ContentNegotiationConfigurer to your needs, eg. by calling
ContentNegotiationConfigurer#favorParameter
ContentNegotiationConfigurer#favorPathExtension
If you set both to false
, then Spring will look at the Accept
header. Since your client can say Accept: image/*,application/json
and handle both, Spring should be able to return either the image or the error JSON.
See this Spring tutorial on content negotiation for more information and examples.