2阶——ServletContext对象,与简单的文件上传下载
1:ServletContext对象主要的作用: (域对象,获取mime, 获取服务文件的路径)
//在一个servlet中,几种获取servletContext对象的方式 request.getServletContext(); this.getServletContext(); //this这里其实代表的是tomcat对象 ServletConfig servletConfig = this.getServletConfig(); servletConfig.getServletContext();
>获取mime类型
ServletContext servletContext = this.getServletContext(); String mimeType = servletContext.getMimeType("a.jpg"); System.out.println(mimeType); //图片的mime是 image/jpeg
>获取文件的真实路径(服务器)
//当资源文件在web下时的获取方式 String webpaht = servletContext.getRealPath("/b.properties"); System.out.println("webpath"+webpaht); //webpath D:\WebDemo01\out\artifacts\WebDemo01_war_exploded\b.properties //当资源文件在WebInf下时的获取方式 String webInfPath = servletContext.getRealPath("/WEB-INF/c.properties"); System.out.println("webInfPath"+webInfPath); //webInfPath D:\WebDemo01\out\artifacts\WebDemo01_war_exploded\WEB-INF\c.properties //当资源文件在src下时的获取方式 String srcPath = servletContext.getRealPath("/WEB-INF/classes/a.properties"); System.out.println("srcPath"+srcPath); //srcPath D:\WebDemo01\out\artifacts\WebDemo01_war_exploded\WEB-INF\classes\a.properties
//简单文件上传原理
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接受传递过来的文件名字
String filename = request.getParameter("filename");
//获取它的mime类型 String mimeType = this.getServletContext().getMimeType(filename); //获取需要下载文件的路径 String path = this.getServletContext().getRealPath("/img/" + filename); FileInputStream fin = new FileInputStream(path); //加载进内存 String filename_new = new Date().getTime()+filename; response.setHeader("content-type",mimeType);
//解决中文文件名乱码问题
String agent = request.getHeader("user-agent");
filename_new = DownLoadUtils.getFileName(agent,filename_new);
response.setHeader("content-disposition","attachment;filename="+filename_new); ServletOutputStream os = response.getOutputStream();
byte[] bytes = new byte[1024]; int len = 0; while ( (len = fin.read(bytes) )!= -1){ os.write(bytes,0,bytes.length); } fin.close(); }
上传文件名乱码问题
坚持