黑马程序员技术交流社区

标题: 提供一个java 下载功能的代码 给大家分享下 [打印本页]

作者: qianfancy    时间: 2012-11-28 08:47
标题: 提供一个java 下载功能的代码 给大家分享下
String fileName = "F:\\pdf\\SQL语句大全大全(经典珍藏版).pdf"; // 里面可以提供本地下载路径
                String fname="jjj.pdf";
                File imgFile = new File(fileName);
                try{
                        if(imgFile.exists()){
                                response.setContentType("application/octet-stream");
                                String fn = URLEncoder.encode(fname, "UTF-8");
                                fn = fn.replace("+", "%20");// 浏览器解析为空格了
                                response.setHeader("Content-Disposition", "attachment;filename=\""+ fn + "\"");
                                File file = new File(fileName);
                                response.setContentLength(Integer.parseInt(file.length() + ""));
                                InputStream fs = new FileInputStream(file);
                                OutputStream os = response.getOutputStream();
                                byte[] buff = new byte[1024];
                                int readCount = 0;
                                while ((readCount = fs.read(buff)) != -1) {
                                        os.write(buff, 0, readCount);
                                }
                                fs.close();
                                response.flushBuffer();
                               
                        }else{
                                System.out.print("文件没找到!");
//                                response.setContentType("text/html;charset=UTF-8");
//                                response.getWriter().print("对不起,文件没找到!");
                        }
                }catch(Exception e){
                       
                }
作者: tfy    时间: 2012-12-1 00:07
不错哦 可以学习呀




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2