springMVC系列之@Responsebody接口弹出f.t
2020-05-28 本文已影响0人
smileNicky
@TOC
最近遇到一个文件上传接口,调用时候出现f.txt下载问题,这个估计很多人都有遇到过,网上找资料,很多博客都是说用如下类似代码:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
反正基本大同小异,不过我测试过,在ie,360极速浏览器都有问题,Spring的版本是4.2.2.RELEASE
接口代码如:
@RequestMapping("/updateHandInfo")
@ResponseBody
public ResultModel updateHandInfo(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,
HandleDto handleDto)throws Exception{
try {
...
return new ResultModel(true,"签收成功",resultMap);
} catch (Exception e) {
logger.error("签收失败",e);
return new ResultModel(false,"签收失败",null);
}
}
用网上的方法没解决问题,只能改变一下了,用response的方法,代码改造如:
@RequestMapping("/updateHandInfo")
//@ResponseBody
public void updateHandInfo(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,
HandleDto handleDto,,HttpServletResponse response)throws Exception{
String jsonStr = "";
try {
...
jsonStr = JSONObject.toJSONString(new ResultModel(true,"签收成功",resultMap));
} catch (Exception e) {
logger.error("签收失败",e);
jsonStr = JSONObject.toJSONString(new ResultModel(false,"签收失败","0"));
}
// fix bug 直接通过response返回
this.toJson(response, jsonStr);
}
protected void toJson(HttpServletResponse response,String jsonString) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(jsonString);
}
ResultModel 是封装的Model,这种方法虽然比较麻烦点,不过是可以解决问题的,所以本博客记录起来,仅供互相学习参考