标签:获取文件的绝对路径 generate content http let pre ted puts 文件名
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DownloadServlet */ public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取需要下载文件名称 String filename = request.getParameter("filename"); //获取下载的类型 response.setContentType(this.getServletContext().getMimeType(filename)); //告知客户端需要下载 response.setHeader("Content-Disposition", "attachment;filename="+filename); //获取文件的绝对路径 String path = this.getServletContext().getRealPath("download/"+filename); //获取文件的输入源 InputStream in = new FileInputStream(path); //获取输出流 ServletOutputStream out = response.getOutputStream(); int len=0; byte[] buffer = new byte[1024]; while((len=in.read(buffer))>0) { out.write(buffer,0,len); } in.close(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
标签:获取文件的绝对路径 generate content http let pre ted puts 文件名
原文地址:http://www.cnblogs.com/sangewuxie/p/7481688.html