public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final int BUFSIZE = 4096; String filePath = null; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { filePath = getServletContext().getRealPath("") + File.separator + "abc.txt"; File file = new File(filePath); int length = 0; ServletOutputStream outStream = response.getOutputStream(); response.setContentType("text/html"); response.setContentLength((int) file.length()); String fileName = (new File(filePath)).getName(); response.setHeader("Content-Disposition", "attachment; filename=/""+ fileName + "/""); byte[] byteBuffer = new byte[BUFSIZE]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((length = in.read(byteBuffer)) != -1)) { outStream.write(byteBuffer, 0, length); } in.close(); outStream.close(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10563.html