在SpringMVC的开发过程中,有时需要实现文档的下载功能。文档的下载功能涉及到了java IO流操作的基础知识,下面本文详细介绍java如何实现后台文档下载功能。
首先根据文档在项目中的存储路径建立File对象,并获取文档的名称和后缀。判断浏览器类型,防止中文文件名出现乱码。
File file=new File(path);
String fileName=file.getName();
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
String agent=(String)request.getHeader("USER-AGENT"); //判断浏览器类型
try {
if(agent!=null && agent.indexOf("Fireforx")!=-1) {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); //UTF-8编码,防止输出文件名乱码
}
else {
fileName=URLEncoder.encode(fileName,"UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
之后,初始化读入字节流和读出字节流,并设置响应response的输出属性。
BufferedInputStream bis=null;
OutputStream os=null;
response.reset();
response.setCharacterEncoding("utf-8");
if(ext=="docx") {
response.setContentType("application/msword"); // word格式
}else if(ext=="pdf") {
response.setContentType("application/pdf"); // word格式
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
接着调用inputStream和outputStream的read、write函数进行IO流读写操作。最后在写出操作完成后,一定要关闭输出流。
try {
bis=new BufferedInputStream(new FileInputStream(file));
byte[] b=new byte[bis.available()+1000];
int i=0;
os = response.getOutputStream(); //直接下载导出
while((i=bis.read(b))!=-1) {
os.write(b, 0, i);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就可以使用java完成word、pdf文档的下载功能。