解決Spring Boot @Responsebody後IE瀏覽器返回json時提示下載問題
阿新 • • 發佈:2019-01-12
解決Spring boot返回JSON物件後在IE客戶端會提示下載JSON檔案的問題
- Spring boot版本1.5.3.RELEASE
- 問題詳細原因:在一個通用上傳下載介面中,使用@[email protected](method=RequestMethod.POST, produces = “application/json; charset=UTF-8”),這樣返回的為JSON物件
其實這樣返回在除IE(又是IE)外的瀏覽器一般都沒有問題,但是如果IE中前端使用iframe框架的話,IE就會將JSON物件當成下載檔案(即使是IE11這樣支援application/json的也不行),解決這個問題應該有不少辦法,網上找了找都不行,最後還是自己嘗試著解決,詳細過程:
- 將@RequestMapping(method=RequestMethod.POST, produces = “application/json; charset=UTF-8”)中的produces屬性改為"text/plain"普通文字形式
- 在spring上下文中新增一個支援text/plain的訊息轉換器
@Configuration public class MvcConfig extends WebMvcConfigurerAdapter { /** * 解決低版本ieresponsebody返回json的時候提示下載問題 * @return */ public FastJsonHttpMessageConverter getFastJsonHttpMessageConverter() { //1.需要定義一個convert轉換訊息的物件; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2處理ie瀏覽器儲存資料時出現下載json資料問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.TEXT_PLAIN); //3.在convert中新增配置資訊. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); return fastJsonHttpMessageConverter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(getFastJsonHttpMessageConverter()); } }