首页 > 代码库 > Java下载文件(流的形式)

Java下载文件(流的形式)

 1     @RequestMapping("download")
 2     @ResponseBody
 3     public void download(HttpServletResponse response, Integer userId, String fileUrl) { 
 4         try {
 5             File file=new File(fileUrl);
 6             String filename=file.getName();
 7             // 以流的形式下载文件。
 8             InputStream fis = new BufferedInputStream(new FileInputStream(fileUrl));
 9             byte[] buffer = new byte[fis.available()];
10             fis.read(buffer);
11             fis.close();
12             // 清空response
13             response.reset();
14             
15             response.setContentType("application/octet-stream;charset=UTF-8");
16             String fileName = new String(filename.getBytes("gb2312"), "iso8859-1");
17             response.setHeader("Content-disposition", "attachment;filename=" + fileName);
18             OutputStream ouputStream = response.getOutputStream();
19             ouputStream.write(buffer);
20             ouputStream.flush();
21             ouputStream.close(); 
22         } catch (Exception e) {
23             e.printStackTrace();
24             logger.error("文件下载出现异常", e); 
25         } 
26     }    

 

Java下载文件(流的形式)