您的位置:首页 > 编程语言 > Java开发

访问服务器地址中的某个文件链接,下载文件到客户端

2016-06-28 20:52 495 查看
public void download() {  

        java.io.BufferedInputStream bis = null;  

        java.io.BufferedOutputStream bos = null;

        HttpServletRequest request = ThreadContextHolder.getHttpRequest();
HttpServletResponse response = ThreadContextHolder.getHttpResponse();
Integer yml_id = Integer.valueOf(request.getParameter("yml_id"));
YmlModel yml = this.logiManager.queryforYml(yml_id);
String file = null;
String fileUrl="";

String savePath = request.getRealPath("/")+"test/upyml/";
if(yml!=null){
file = yml.getYml_upfile();
}
String fileName=file;
fileUrl=savePath+file;

        try {  

            fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");  

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

            response.setCharacterEncoding("utf-8");  

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

                    + fileName);  

            // 通知客户文件的MIME类型:  

            bis = new java.io.BufferedInputStream(new java.io.FileInputStream(  

                    (fileUrl)));  

            bos = new java.io.BufferedOutputStream(response.getOutputStream());  

            byte[] buff = new byte[2048];  

            int bytesRead;  

            int i = 0;  

  

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

                bos.write(buff, 0, bytesRead);  

                i++;  

            }  

            bos.flush();

            this.showSuccessJson("下载成功!");

        } catch (Exception e) {  

            e.printStackTrace();

            this.showSuccessJson("下载失败!");

        } finally {  

            if (bis != null) {  

                try {  

                    bis.close();  

                } catch (IOException e) {  

                    // TODO Auto-generated catch block  

                    e.printStackTrace();  

                }  

                bis = null;  

            }  

            if (bos != null) {  

                try {  

                    bos.close();  

                } catch (IOException e) {  

                    // TODO Auto-generated catch block  

                    e.printStackTrace();  

                }  

                bos = null;  

            }  

        }  

  
    }  

其中fileUrl为服务器中的文件真实路径,fileName为文件名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  下载文件 java download