用servlet下载文件小结
用servlet实现了一个小小的文件下载,主要步骤是:
1获取要下载的文件
2定义Response的文件头,例如文件名/文件类型/长度之类
3用InputStream读取文件,并转成ServletOutputStream输出
?
protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {System.out.println("service");//获取要下载的文件File downloadFile = new File(req.getSession().getServletContext().getRealPath("").toString() + "/id");//获取文件长度Long length = downloadFile.length();//设置下载文件的格式,此处为vcardresp.setContentType("text/x-vcard");//添加文件长度的值,作用尚不明确resp.setContentLength(length.intValue());//添加响应报头,下载文件的名称由filename定义resp.addHeader("Content-Disposition", "attachment; filename=contact");if (!downloadFile.exists()) {System.out.println("DownloadServlet: download file dose not exist");return;}ServletOutputStream sos = resp.getOutputStream();//将文件转成字节流输入BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFile));int size = 0;byte[] b = new byte[4096];//每次读取4个字节,并写入输出流之中while ((size = bis.read(b)) != -1) {sos.write(b, 0, size);}sos.flush();sos.close();bis.close();}?参考文章:http://www.cnblogs.com/windlaughing/archive/2013/04/22/3036148.html