文件所在位置:/DownLoadDemo/WebRoot/download/001.jpg
///DownLoadDemo/src/com/huowolf/DownLoadServlet.java
package com.huowolf; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownLoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String path = this.getServletContext().getRealPath("/download/001.jpg"); String filename = path.substring(path.lastIndexOf("\\")+1); //response.setHeader("Content-Type", "application/octet-stream"); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment;filename="+filename); InputStream in = null; OutputStream out = response.getOutputStream(); out.write("下载示例".getBytes()); try { in = new FileInputStream(path); int len=-1; byte buffer[] = new byte[1024]; while((len=in.read(buffer))!=-1) { out.write(buffer,0,len); } } catch (Exception e) { e.printStackTrace(); }finally { if(in!=null) { try { in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
原文地址:http://blog.csdn.net/huolang_vip/article/details/46509733