对于word以及excel我并没有多少好感,但是今天工作需要不得不去亲近它了,但是后来发现这个就像人们的关系一样,你亲近它,它就亲近你。好了,废话不多说了,咱们就来看看,到底是怎样实现这个下载的。
我们的项目,是将word放到了项目中,所以就是一个死路径,我们只需要去读这个路径就可以了,所以前台不许多说,只需要传过来路径,去调用后台方法即可。我们就来看看后台。
public void download(){
String fileName = request.getParameter("fileid");
try {
request.setCharacterEncoding("utf-8");
fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");
//获取文件路径
String filePath = "E:\\THSPlatform\\projects\\serviceGuide-archetype\\src\\main\\webapp\\WEB-INF\\conf\\res\\servicecontent\\baseword\\"+fileName;
filePath = filePath == null ? "" : filePath;
//设置向浏览器端传送的文件格式
response.setContentType("application/x-download");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ fileName);
FileInputStream fis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(filePath);
byte[] b = new byte[1024 * 10];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
当然这是最简单的一种实现方式,因为路径是死的,如果是生成word可能会稍微麻烦一点,但是我们通过代码不难发现,无非就是一些设置文件读取之类的代码,而并没有自己想象的那么难。所以任何事情都应该先去做,不要自己觉得难就不去做。