java下载文件

// 文件名称中文乱码new String(filename.getBytes("iso8859-1"), "utf8");很重要

  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;
  try {
//接收文件名
    String filename = request.getParameter("filename");
//将utf8编码的文件名转ISO-8859-1编码
    filename = new String(filename.getBytes("iso8859-1"), "utf8");

    response.setContentType("application/x-msdownload");
//将文件名由ISO-8859-1编码转换为UTF-8编码存入相应头中
    response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf8"), "iso8859-1"));
//写入流读取绝对位置文件
    bis = new BufferedInputStream(new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"docs/"+filename));
//将response流给写入流
    bos = new BufferedOutputStream(response.getOutputStream());

    byte[] buff = new byte[1024];

    int bytesRead;

    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {

      bos.write(buff, 0, bytesRead);

    }

  } catch (Exception e) {

    e.printStackTrace();

  } finally {
//关闭写入流
    if (bos != null)bos.close();
//关闭读取流
    if (bis != null)bis.close();

  }

你可能感兴趣的:(java)