3.文件下载

1.普通文件下载
使用超链接。缺点:1)暴露文件的路径 2)扩展型和安全性不好
2.使用servlet程序下载(推荐)
 //1.得到响应的下载内容
        String fileName = "abc.txt";
        InputStream in = this.getServletContext().getResourceAsStream("/upload/"+fileName);
        //对文件名进行url编码设置
        fileName = URLEncoder.encode(fileName,"utf-8");
        //判断不同的浏览器
        String userAgent = req.getHeader("user-agent");
        String filefix = null;
        System.out.println(userAgent);
        if (userAgent.contains("Trident")){
            //IE
            filefix = "filename="+fileName;
        }else if (userAgent.contains("Firefox")) {
            //Fire
            filefix = "filename*=" + fileName;
        }else{
            filefix = "filename="+fileName;
        }
        //告诉浏览器去用以下的方式去打开
        resp.setHeader("Content-Disposition","attachment;"+filefix);

        //2.把本地文件发送给浏览器
        OutputStream out = resp.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len=in.read(buf))!=-1){
            out.write(buf,0,len);
        }
        //关闭流
        out.close();
        in.close();
    }

你可能感兴趣的:(3.文件下载)