@
目录
最近遇到一个文件上传接口,调用时候出现f.txt下载问题,这个估计很多人都有遇到过,网上找资料,很多博客都是说用如下类似代码:
text/json;charset=UTF-8
text/html;charset=UTF-8
application/json;charset=UTF-8
反正基本大同小异,不过我测试过,在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,这种方法虽然比较麻烦点,不过是可以解决问题的,所以本博客记录起来,仅供互相学习参考