Response实现文件下载

使用Myeclipse 工具

       在WebRoot目录下创建一个Download文件夹(new-->folder),以存放 附件(图片,文件...),

 

具体实现下载功能的代码如下

 

package cn.response; import java.io.*; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //response实现从服务器上,下载文件 public class Response_download extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = this.getServletContext().getRealPath("/Download/定南中学.jpg");//获取文件的相对路径 String filename = path.substring(path.lastIndexOf("\\")+1);//获取文件名称,在转化为子串 //response.setHeader告诉浏览器以什么方式打开 //假如文件名称是中文则要使用 URLEncoder.encode()编码 //否则直接使用response.setHeader("content-disposition", "attachment;filename=" + filename);即可 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); InputStream in = null ; OutputStream out = null ; try { in = new FileInputStream(path); //获取文件的流 int len = 0; byte buf[] = new byte[1024];//缓存作用 out = response.getOutputStream();//输出流 while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“ { out.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取 } }finally { if(in!=null) { try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } if(out!=null) { try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

 

注意:
        try{...}  finally{...}

        如果 try{...} catch{...}  中没有 catch{...},则必须要加上 finally{...}

        finally{...} 一般用来关闭流这些,不管有没有异常,

 

 

你可能感兴趣的:(Response实现文件下载)