日期:2014-05-18 浏览次数:20737 次
import java.io.FileInputStream; import java.io.IOException; 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; public class DownloadFileServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename=request.getParameter("filename"); response.reset(); response.setContentType("application/x-download"); UploadFile upload = new UploadFile(); String filepath = upload.getDownloadFilePath(); String filenamedownload = filepath + java.io.File.separator + filename; String filenamedisplay = java.net.URLEncoder.encode(filename, "UTF-8"); filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay); OutputStream output = null; FileInputStream fis = null; try { output = response.getOutputStream(); fis = new FileInputStream(filenamedownload); byte[] b = new byte[1024]; int i = 0; while ((i = fis.read(b)) > 0) { output.write(b, 0, i); } output.flush(); } catch (Exception e) { System.out.println("Close the download file windows!"); } finally { if (fis != null) { fis.close(); fis = null; } if (output != null) { output.close(); output = null; } } } }