标签:protected 头信息 attach utf-8 class tcl new prot png
下面的代码简单的实现了java下载文件的步骤,看代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取文件的类名 String Path=this.getClass().getResource("/").getPath()+"JAVA笔记.txt"; //对获取的路径进行解码 Path=URLDecoder.decode(Path); //获取文件名字和扩展名 String FileName=Path.substring(Path.lastIndexOf("/")+1,Path.length()); //设置输出文件名编码 FileName=URLEncoder.encode(FileName, "UTF-8"); //设置头信息 response.setHeader("content-disposition", "attachment;filename="+FileName); response.setContentType("application/octet-stream"); //获取文件流对象 FileInputStream file=new FileInputStream(Path); //定义字节数组,长度为文件流的长度 byte[] buffers=new byte[file.available()]; //获取输出流对象 OutputStream writer=response.getOutputStream(); //把流输出到字节数组中去 file.read(buffers); //写到页面 writer.write(buffers); //关闭流 writer.close(); file.close(); }
效果图:
标签:protected 头信息 attach utf-8 class tcl new prot png
原文地址:http://www.cnblogs.com/wwj1992/p/6123727.html