JAVA实现文件下载的功能

文件的下载

实现思想

浏览器通过访问服务器提供的servlet,返回一个显示可下载的文件列表,点击相应要下载的文件,则会访问一个下载的servelt,实现文件的下载功能

实现代码

UploadUtils.java工具类

public class UploadUtils {
    //创建新的文件名称
    public static String createNewFileName(String filename){
        String s = UUID.randomUUID().toString().replace("-", "");
        return s+"_"+filename;
    }
    //上传文件时创建不同的上传路径,防止图片过多,打开效率低下
    public static String createNewPath(String path,String filename){
        int i = filename.hashCode();
        int path1=i&0xf;
        int path2=(i>>4)&0xf;
        String realPath=path+ File.separator+path1+File.separator+path2;
        File dir=new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        return realPath;
    }
    //遍历文件夹,将已经下载的文件都找出来放到一个集合中
    //HashMap中的key存带有UUid的文件名,value存不带UUID的文件名
    public static void listFile(File dir, HashMap<String,String> map){
        //遍历获得特定路径的文件夹和文件绝对目录
        File[] files = dir.listFiles();
        for (File file : files) {
            if(file.isDirectory()){
                //如果遍历到的是文件夹,那么则进行递归遍历
                listFile(file,map);
            }else{
                //如果遍历到的是文件
                String uuidName = file.getName();
                String name=uuidName.substring(uuidName.indexOf("_")+1);
                map.put(uuidName,name);
            }
        }

    }

}

ListFileServlet.java

@WebServlet(name = "ListFileServlet",value = "/listfile")
public class ListFileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取可以被下载的文件,显示到前端页面
        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        HashMap<String,String> hashMap=new HashMap<>();
        UploadUtils.listFile(new File(realPath),hashMap);
        //转发
        request.setAttribute("map", hashMap);
        request.getRequestDispatcher("/display.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    }
}

DownLoadServlet.java

@WebServlet(name = "DownLoadServlet",value = "/download")
public class DownLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取带有UUID的文件名
        String uuidFilename = request.getParameter("filename");
        //去掉UUID
        String filename=uuidFilename.substring(uuidFilename.indexOf("_")+1);
        //获得文件存放的根路径
        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        //找到对应文件所处的准确位置
        String path = UploadUtils.createNewPath(realPath, filename);
        System.out.println(path);
        File file=new File(path+File.separator+uuidFilename);
        if(file.exists()){
            //文件存在
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
            ServletOutputStream os = response.getOutputStream();
            FileInputStream fis=new FileInputStream(file);
            byte[] buf=new byte[1024*4];
            int len=0;
            while((len=fis.read(buf))!=-1){
                    os.write(buf,0,len);
            }
        }else{
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("下载失败");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    }
}

display.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>文件下载</title>
</head>
<body>

<ul>
    <c:forEach var="entry" items="${map}">
        <c:url var="myurl" value="/download">
            <c:param name="filename" value="${entry.key}"></c:param>
        </c:url>
        <li><a href="${myurl}">${entry.value}</a></li>
    </c:forEach>
</ul>
</body>
</html>

启动服务器测试即可,文件上传功能在之前的博客中已经实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值