1.获取项目根目录:
@Override public void init() throws ServletException { // 获取项目在文件系统中的根目录 string = getServletContext().getRealPath(File.separator); }
init()方法在整个Servlet生命周期内只会被加载一次,用于数据的初始化。
2.下载文件代码:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //配置文件路径 String filePath = string + "download" + File.separator + "18612.jpg"; //通过UUID获取宇宙唯一文件名,并将其中‘-’连接符去掉 String fileName=UUID.randomUUID().toString().replace("-", ""); // 设置下载文件名 response.setHeader("content-disposition", "attachment;filename="+fileName+".jpg"); // 获取输出流 ServletOutputStream outputStream = response.getOutputStream(); // 把文件写入tomcat InputStream inputStream = new FileInputStream(new File(filePath)); byte[] b = new byte[1024]; int len = 0; while ((len = inputStream.read(b)) != -1) { //输出到浏览器 outputStream.write(b, 0, len); } if (inputStream!=null) { inputStream.close(); } if (outputStream!=null) { outputStream.close(); } }