标签:文件下载
1.文件下载..
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8")); 通知浏览器以下载的方式打开文件...
response.setContentType(this.getServletContext().getMimeType(filename));//通知浏览器下载的MIME类型
2.文件下载的servlet
package cn.itheima.download; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itheima.utils.IOUtils; public class DownLoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取要下载的文件 String filename = request.getParameter("file"); response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));//告知浏览器要以下载的方式打开...而不是直接打开 response.setContentType("");//告知浏览器文件的类型 InputStream in=new FileInputStream(this.getServletContext().getRealPath(filename)); OutputStream out=response.getOutputStream(); IOUtils.In2Out(in, out); IOUtils.closeIO(in, null); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }2.工具类IOUtils
提供了两个方法一个是读取in中的流中的数据写到out流中
另一个是关闭资源流的函数、
package cn.itheima.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IOUtils { private IOUtils(){ } /** * 读取流中的数据写到输出流中 * @param in * @param out * @throws IOException */ public static void In2Out(InputStream in,OutputStream out) throws IOException{ int len=0; byte b[]=new byte[1024]; while((len=in.read(b))!=-1){ out.write(b, 0, len); } } /** * 关闭资源 * @param in * @param out */ public static void closeIO(InputStream in,OutputStream out){ if(in!=null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); }finally{ in=null; } } if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); }finally{ out=null; } } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:文件下载
原文地址:http://blog.csdn.net/u014010769/article/details/46822085