HttpMediaTypeNotAcceptableException: Could not find acceptable representation in exceptionhandler

前端 未结 2 463
梦如初夏
梦如初夏 2020-12-01 18:27

I have the following image download method in my controller (Spring 4.1):

@RequestMapping(value = \"/get/image/{id}/{fileName}\", method=RequestMethod.GET)
p         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 19:05

    You need to decide how the media type of the response should be determined by Spring. That can be done in several ways:

    • path extension (eg. /image.jpg)
    • URL parameter (eg. ?format=jpg)
    • HTTP Accept header (eg. Accept: image/jpg)

    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.

提交回复
热议问题