返回顶部

收藏

Servlet 下载文件代码

更多
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();
    }

}

标签:java

收藏

0人收藏

支持

0

反对

0

发表评论