文件下载代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


String filename = request.getParameter("filename");    //获取要下载的文件名
response.setHeader("Content-Disposition", "attachment;filename="+filename);  //让浏览器收到这份资源时,以下载的方式提醒,而不是展示;
String path = getServletContext().getRealPath("download/"+filename);  // 使用context  , 获取文件绝对路径

InputStream is = new FileInputStream(path) ;  //创建输入流进内存
OutputStream os = response.getOutputStream();   //创建字节输出流
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer))!=-1) {
os.write(buffer,0,len);     //像浏览器写入
}
os.close();
is.close();
}

你可能感兴趣的:(文件下载代码)