• 文件下载


    servlet   MoreDownloadServlet.java:

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cn.itcast.util.FirxFoxUtil;
    
    
    /**
     * 下载案例后台
     * @author Administrator
     *
     */
    public class MoreDownloadServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 获取绝对路径
            String filepath = request.getParameter("filepath");
            filepath = new String(filepath.getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("文件的绝对路径:"+filepath);
            String filename = null;
            // 截取文件的名称
            int index = filepath.lastIndexOf("\");
            if(index != -1){
                filename = filepath.substring(index + 1);
            }
            
            // 先判断是什么浏览器
            String agent = request.getHeader("USER-AGENT");
            System.out.println(agent);
            // 判断当前是什么浏览器
            if(agent.contains("Firefox")){
                // 采用BASE64编码
                filename = FirxFoxUtil.base64EncodeFileName(filename);
            }else{
                // IE GOOGLE
                filename = URLEncoder.encode(filename, "UTF-8");
                // URL编码会空格编成+
                filename = filename.replace("+", " ");
            }
            
            // 创建file对象
            File file = new File(filepath);
            // 输入流
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            // 设置两个响应头
            response.setContentType(this.getServletContext().getMimeType(filename));
            response.setHeader("Content-Disposition", "attachment;filename="+filename);
            // 一个流
            OutputStream os = response.getOutputStream();
            int b;
            while((b = in.read()) != -1){
                os.write(b);
            }
            os.close();
            in.close();
        }
    
    }

    util:

    Base64Util.java

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import sun.misc.BASE64Encoder;
    
    public class Base64Util {
        public static void main(String args[]) throws IOException {
            System.out.print("请输入用户名:");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String userName = in.readLine();
            System.out.print("请输入密码:");
            String password = in.readLine();
            BASE64Encoder encoder = new BASE64Encoder();
            System.out.println("编码后的用户名为:" + encoder.encode(userName.getBytes()));
            System.out.println("编码后的密码为:" + encoder.encode(password.getBytes()));
        }
    }

    FirxFoxUtil.java:

    import java.io.UnsupportedEncodingException;
    
    import sun.misc.BASE64Encoder;
    
    public class FirxFoxUtil {
        
        public static String base64EncodeFileName(String fileName) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            try {
                return "=?UTF-8?B?"
                        + new String(base64Encoder.encode(fileName
                                .getBytes("UTF-8"))) + "?=";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    
    
    }

    jsp  moredownload.jsp:

    <%@page import="java.net.URLEncoder"%>
    <%@page import="java.io.File"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'moredownload.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
      <%
          // 指定一个根目录
          String rootpath = "E:\downfile";
          // 创建File对象
          File rootfile = new File(rootpath);
          // 创建队列
          Queue<File> queue = new LinkedList<File>();
          // 把根目录入队
          queue.offer(rootfile);
          while(!queue.isEmpty()){
              // 先把根目录出队
              File file = queue.poll();
              File [] files = file.listFiles();
              // 循环遍历,拿到每一个file对象,操作file的判断是否是文件还是文件夹
              for(File f : files){
                  if(f.isFile()){
                      // 文件
      %>
              <a href="/day22/moredownload?filepath=<%=URLEncoder.encode(f.getCanonicalPath(), "UTF-8")%>"><%=f.getName() %></a><br/>
      <%                
                  }else{
                      //文件夹
                      queue.offer(f);
                  }
              }
          }
      
       %>
      </body>
    </html>
  • 相关阅读:
    音乐播放器-任务
    android 四大组件Broadcast Receiver
    Android面试题
    android Notification 的使用
    【转】dip,px,pt,sp 的区别
    SQL Server快捷方式丢了怎么启动
    《ASP.NET1200例》C#在网页上编写动态时钟
    Win7旗舰版中的IIS配置asp.net的运行环境
    《转》Win7 IIS7.5 安装
    《ASP.NET 1200例》ref关键字与out关键字
  • 原文地址:https://www.cnblogs.com/appium/p/10286017.html
Copyright © 2020-2023  润新知