java web项目文件下载

来源:互联网 发布:淘宝男装设计师品牌 编辑:程序博客网 时间:2024/05/16 14:05

    Java web项目中经常会设计到文件下载的功能,以下代码就来实现这个功能。

   String path = "D:\\source.txt";   //path是根据文件路径和文件名拼接出来的

    // 下面注释代码中根据获取的fileid获得-- 文件的路径和文件名

    //String fileid = request.getParameter("fileid");
    //        if (fileid == null || fileid.equals("")) {
    //            request.setAttribute("causation", "缺少相关信息:请求无效!");
    //            return mapping.findForward("failure");
    //        }
    //        String path = request.getSession().getServletContext().getRealPath(
    //                File.separator);
    //        path = path + "WEB-INF" + File.separator + "uploads"
    //                + File.separator + fileid;

    File file = new File(path); 

    if (!file.exists()) {
               System.out.print("文件不存在!");
            }

    String filename = file.getName();// 获取文件名称

    FileInputStream in = new FileInputStream(file);

    InputStream fis = new BufferedInputStream(in);
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    response.reset();
    // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream os = new BufferedOutputStream(response.getOutputStream());

    response.setContentType("application/octet-stream");

    os.write(buffer);// 输出文件
    os.flush();
    os.close();
0 0
原创粉丝点击