我用的是swagger 前后台分离的项目
我的需求是从服务器端的某磁盘中获取按模板生成的word文件,并下载。
思路: 按模板在服务器上生成一个word文档 通过流的方式读取word响应给浏览器 最后删除在服务器生成的word文档
public void word(String unitid,HttpServletResponse response) throws Exception {
Map map=getMapper().xkzzb(unitid);
Set keySet = map.keySet();
/**
* 在服务器上产生文件
*/
MSWordManager ms = new MSWordManager(false);
//File file = ResourceUtils.getFile("classpath:dot/xxx.dot"); 读取本机的
//读取服务器的
String path = this.getClass().getResource("/").getPath();
String filePath = path.substring(1, path.length() - 16);
filePath+="WEB-INF/classes/dot/xxx.dot";
ms.openDocument(filePath);//file.getPath()
String savePath = null;
try {
savePath = "C:\\xxx" + UUID.randomUUID()
+ ".doc";
ms.save(savePath);
for(String key:keySet) {
if(key.equals("PERIOD_VALIDITY")) {
//时间切割
String object = DateToString((Date)map.get(key));
String[] split = object.split("-");
//根据标签填充数据
ms.intoValueBookMark("PERIOD_YEAR",split[0]);
ms.intoValueBookMark("PERIOD_MOD",split[1]);
ms.intoValueBookMark("PERIOD_DAY",split[2]);
//删除标签
ms.deleteBookMark("PERIOD_YEAR","");
ms.deleteBookMark("PERIOD_MOD","");
ms.deleteBookMark("PERIOD_DAY","");
}else if(key.equals("OPENING_DATE")) {
//时间切割
String object = DateToString((Date)map.get(key));
String[] split = object.split("-");
//根据标签填充数据
ms.intoValueBookMark("OPENING_YEAR",split[0]);
ms.intoValueBookMark("OPENING_MOD",split[1]);
ms.intoValueBookMark("OPENING_DAY",split[2]);
//删除标签
ms.deleteBookMark("OPENING_YEAR","");
ms.deleteBookMark("OPENING_MOD","");
ms.deleteBookMark("OPENING_DAY","");
}else {
ms.intoValueBookMark(key,(String)map.get(key));
ms.deleteBookMark(key,"");
}
}
}finally{
ms.close();
ms.closeDocument();
}
//===============主要下载的代码======================
/**
* 下载
*/
FileInputStream in = null;
OutputStream out = null;
try {
//获取文件名
String filename = savePath.substring(savePath.lastIndexOf("/")+1);
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String downloadpath = savePath;
//File file = new File(path1);
//如果文件不存在
/*if(!file.exists()){
return false;
}*/
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//读取要下载的文件,保存到文件输入流
in= new FileInputStream(downloadpath);
//创建输出流
out= response.getOutputStream();
//缓存区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区中
while((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
}finally {
//关闭
in.close();
out.close();
}
//删除服务器上的临时文件
File deleteFile=new File(savePath);
deleteFile.delete();
}