文件下载
public void handle(HttpServletRequest request,HttpServletResponse response) {
try {
String modlename="文件FOO.doc";
String templateFilePath = "D:"+File.separator+modlename;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
OutputStream fos=null;
InputStream fis = null;
File file = new File(templateFilePath);
fis= new FileInputStream(file);
bis = new BufferedInputStream(fis);
//getWriter() has already been called for this response(异常解决)
response.reset();
fos= response.getOutputStream();
bos= new BufferedOutputStream(fos);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
response.setHeader("Content-disposition", "attachment;filename="+java.net.URLEncoder.encode(modlename, "UTF-8"));
int bytesRead=0;
byte[] buffer= new byte[8192];
while((bytesRead=bis.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);
}
bos.flush();
bis.close();
bos.close();
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
文件放在服务器目录
String realpath1=request.getSession().getServletContext().getRealPath("/"); //建议使用
String realpath =request.getRealPath("/");//过时方法
String filepath=realpath+File.separator+"WEB-INF"+File.separator+"file"+File.separator+modlename;