java文件下载

    public HttpServletResponse UpDowon(String uri,HttpServletResponse response) throws IllegalStateException, IOException
    {
        try {
              //预下载的文件的路径。
              File file = new File(uri);
              // 取得文件名。
              String filename = file.getName();
              // 取得文件的后缀名。
              String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
         
              // 以流的形式下载文件。
              InputStream fis = new BufferedInputStream(new FileInputStream(uri));
              byte[] buffer = new byte[fis.available()];
              fis.read(buffer);
              fis.close();
              // 清空response
              response.reset();
              // 设置response的Header
//              response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("ISO-8859-1")));
              response.setContentType("application/octet-stream;charset=UTF-8");
              response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("gb2312"), "ISO8859-1"));
              response.setHeader("Content-Length", "" + file.length());
              //获取写入流
              OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
              toClient.write(buffer);
              toClient.flush();
              toClient.close();
            } catch (IOException ex) {
              ex.printStackTrace();
            }
        return response;
    }

 

posted on 2018-08-02 11:13  奔走的鱼  阅读(104)  评论(0)    收藏  举报

导航