JSP文件下载

来源:互联网 发布:linux sqlcmd 编辑:程序博客网 时间:2024/04/28 20:58

    File file = new File(URLDecoder.decode(filePath, "GBK"));
    filename = new String(filename.getBytes("gb2312"), "iso8859-1");
    response.reset();//octet-stream  or download
     response.setContentType("application/octet-stream; charset=GBK");
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);
    response.setContentLength((int) file.length());

    byte[] buffer = new byte[4096];
    BufferedOutputStream output = null;
    BufferedInputStream input = null;

    // 写缓冲区:
    try {
        output = new BufferedOutputStream(response.getOutputStream());
        input = new BufferedInputStream(new FileInputStream(file));

        int n = (-1);
        while ((n = input.read(buffer, 0, 4096)) > -1) {
            output.write(buffer, 0, n);
        }
        response.flushBuffer();
    } catch (Exception e) {
    } // maybe user cancelled download
    finally {
        if (input != null)
            input.close();
        if (output != null)
            output.close();
        out.clear();
        out = pageContext.pushBody();
    }