解决Spring Boot 返回 json时在IE浏览器提示下载的问题

要点:

@RequestMapping 增加 produces = MediaType.TEXT_PLAIN_VALUE
MappingJackson2HttpMessageConverter supportedMediaTypes 增加 MediaType.TEXT_PLAIN_VALUE

Spring4.x 为 MappingJackson2HttpMessageConverter
Spring3.x 为 MappingJacksonHttpMessageConverter

代码示例

@RestController
@RequestMapping("/${application.api-path}/import-export")
public class ImportExportController {
 
    @RequestMapping(value = "/import", method = {RequestMethod.POST},produces = MediaType.TEXT_PLAIN_VALUE)
    public JSONResponse _import(HttpServletRequest request,ImportDTO dto) {
        JSONResponse jsonResponse = new JSONResponse();
        try {
            List files = ServletUtils.getMultipartFileList(request);
            
            if (dto != null) {
                if (files != null && files.size() > 0) {
                    dto.setImportFile(files.get(0));
                }
            }
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e);

            jsonResponse.setException(e);
        }

        return jsonResponse;
    }
}
 /**
 * spring mvc 配置
 */
@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter() {

            @Override
            protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
                    throws IOException, HttpMessageNotWritableException {
                super.writeInternal(object, type, outputMessage);
            }
        };

        //#region 处理ie浏览器保存数据时出现下载json数据问题
        
        List fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.TEXT_PLAIN);
        converter.setSupportedMediaTypes(fastMediaTypes);

        //#endregion

        converter.setObjectMapper(JacksonUtils.OBJECT_MAPPER);
        return converter;
    }

    @Override
    protected void configureMessageConverters(List> converters) {
        converters.add(responseBodyConverter());
        converters.add(mappingJackson2HttpMessageConverter());

        super.configureMessageConverters(converters);
    }
}

你可能感兴趣的:(springboot)