实现 post请求下载编码类型为ANSI的TXT文件
@PostMapping(value = "xx")
public void exportLog(HttpServletResponse response, ODupDTO oDupDTO){
String list = oDupDTO.getList();
List<Map<String,String>> maps = new ArrayList<>();
JSON.parseArray(list).forEach(m-> {
Map<String, String> map = new HashMap<>();
JSONObject json = JSON.parseObject(m.toString());
String totalAmount = json.getString("oDkey");
String materiel = json.getString("oDvalue");
map.put("oDkey",totalAmount);
map.put("oDvalue",materiel);
maps.add(map);
});
StringBuffer text = new StringBuffer();
// 拼接字符串
for (Map<String, String> map : maps) {
text.append(map.get("oDkey"));
text.append("\t");
text.append(map.get("oDvalue"));
text.append("\r\n");//换行字符
}
exportTxt(response,text.toString());
}
public void exportTxt(HttpServletResponse response, String text) {
// 这里设置GBK 格式,所以下载出来的TXT文件是ANSI格式
response.setCharacterEncoding("GBK");
//设置响应的内容类型
response.setContentType("text/plain");
//设置文件的名称和格式
response.addHeader("Content-Disposition","attachment;filename="
+ genAttachmentFileName( "文件名称", "JSON_FOR_UCC_")//设置名称格式,没有这个中文名称无法显示
+ ".txt");
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(text.getBytes("GBK"));
buff.flush();
buff.close();
} catch (Exception e) {
//LOGGER.error("导出文件文件出错:{}",e);
} finally {try {
buff.close();
outStr.close();
} catch (Exception e) {
//LOGGER.error("关闭流对象出错 e:{}",e);
}
}
}
public String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
由于下载的时候前台是from表单提交的方式 所以这里是将from表单转换为json字符串格式,然后后台自己进行json解析,解析的json格式如下:
String s = "{\"list\":[{\"oDkey\":\"张三\",\"oDvalue\":\"李四\"},{\"oDkey\":\"赵三\",\"oDvalue\":\"王五\"}]}";
最终下载出的Txt 文件为 ANSI 编码格式 ,此外在网关还配置了下载接口的白名单,以及再子模块下也配置了下载端口的白名单,不需要token就可以进行下载 最终出来的TXT文件如下
如果想要下载出来的格式为UTF-8的只需要将代码中的GBK 改为UTF-8就行。