springMVC系列之@Responsebody接口彈出f.txt下載問題
@
目錄
最近遇到一個文件上傳接口,調用時候出現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,這種方法雖然比較麻煩點,不過是可以解決問題的,所以本博客記錄起來,僅供互相學習參考
IT程序員

浙公網安備 33010602011771號