/**
* 下载doc文件
*
* @param httpServletResponse
* @param id
*/
@RequestMapping("/templateAction_download")
public void downloadFile(HttpServletResponse httpServletResponse, Integer id) {
Template template = templateService.findById(id);
String docfilepath = template.getDocfilepath();
//截取路径中的文件名
String fileName = docfilepath.substring(docfilepath.lastIndexOf("\\")+1);
try {
//读取服务器磁盘上文件的二进制数据
InputStream docStream = new FileInputStream(new File(docfilepath));
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[10000]; //buff用于存放循环读取的临时数据
int rc = 0;
while ((rc = docStream.read(buff, 0, 10000)) > 0) {
swapStream.write(buff, 0, rc);
}
//将输入流转换为字符数组输出流
byte[] docByte = swapStream.toByteArray();
//设置响应头
httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+fileName);
OutputStream os = httpServletResponse.getOutputStream();
os.write(docByte);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论