java下载文件

 1 /**

 2      * 

 3      * @param file

 4      * @param response

 5      */

 6     private void downLoad(File file, HttpServletResponse response,

 7             String browser) throws IOException {

 8         InputStream is = new FileInputStream(file);

 9         try {

10 

11             String fileName = file.getName().replaceAll(" ", "");

12             OutputStream os = response.getOutputStream();

13             BufferedInputStream bis = new BufferedInputStream(is);

14             BufferedOutputStream bos = new BufferedOutputStream(os);

15 

16             if (browser.indexOf("msie") != -1) {

17                 fileName = java.net.URLEncoder.encode(fileName, "UTF-8");

18                 fileName = new String(fileName.getBytes("UTF-8"), "GBK");

19             } else if (browser.indexOf("Firefox") != -1) {

20                 fileName = java.net.URLEncoder.encode(fileName, "UTF-8");

21                 fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");

22             } else if (browser.indexOf("Safari") != -1) {

23                 fileName = new String(fileName.getBytes(), "ISO8859-1");

24             }

25 

26             response.reset();

27             response.setCharacterEncoding("UTF-8");

28             response.setContentType("application/x-msdownload");

29             response.setHeader("Content-Disposition", "attachment; filename="

30                     + fileName);

31             int bytesRead = 0;

32             byte[] buffer = new byte[1024];

33             while ((bytesRead = bis.read(buffer)) != -1) {

34                 bos.write(buffer, 0, bytesRead);

35             }

36 

37             bos.flush();

38             bis.close();

39             bos.close();

40 

41             is.close();

42 

43             os.close();

44 

45         } catch (Exception ex) {

46 

47             log.info("");

48 

49         } finally {

50             is.close();

51         }

52     }

 

你可能感兴趣的:(java)