javaWeb实现文件下载功能

内容

在这里插入图片描述

在这里插入图片描述

实现代码

首先在WEB-INF下创建lib导入包,并添加为库
在这里插入图片描述

1、在utils中建立一个DownLoadUtils.java

import java.io.File;
import java.util.HashMap;

public class DownLoadUtils {
    
    
    public static void getFileList(File file, HashMap<String,String> fileMap){
    
    
        File[] files = file.listFiles();//获取路径下所有文件和文件夹

        for (File f : files) {
    
    
            if (f.isDirectory()){
    
    
                getFileList(f,fileMap);
            }else {
    
    
                String fileName = f.getName();
                int index = fileName.indexOf("_");
                String realName = fileName.substring(index + 1);//获取文件真实名字
                fileMap.put(fileName,realName);
            }
        }
    }
}

2、在servlet中创建FileListController.java

import com.yx.utils.DownLoadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "FileListController",value = "/fileList")
public class FileListController extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        HashMap<String,String> fileMap = new HashMap<>();
        String basePath = request.getServletContext().getRealPath("/WEB-INF/upload");
        DownLoadUtils.getFileList(new File(basePath),fileMap);//原先有UUID的作为key,去除UUID的为value
        request.setAttribute("fileMap",fileMap);
        request.getRequestDispatcher("/list.jsp").forward(request,response);

    }

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

3、在web下创建list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件下载页面</title>
</head>
<body>
    <table>
        <tr>
            <th>文件名</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${fileMap}" var="file">
            <tr>
                <td>${
    
    file.value}</td>
                <td><a href="${pageContext.request.contextPath}/downLoad?fileName=${file.key}">下载</a></td>
            </tr>
        </c:forEach>

    </table>
</body>
</html>

4、最后在servlet中创建DownLoadController.java

import com.yx.utils.UploadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "DownLoadController",value = "/downLoad")
public class DownLoadController extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String basePath = request.getServletContext().getRealPath("/WEB-INF/upload");
        String uuidFileName = request.getParameter("fileName");
        String fileName = uuidFileName.split("_")[1];//分成两部分,取右边,即文件名
        String downPath = UploadUtils.newPath(basePath,fileName);//通过工具类,使用源文件名称获得散列存储路径,就是下载路径

        response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));//设置响应头,浏览器下方弹出下载成功的文件
        FileInputStream is = new FileInputStream(downPath + "\\" + uuidFileName);
        ServletOutputStream sos = response.getOutputStream();
        byte[] buffer = new byte[1024*1024*100];
        int len = 0;
        while((len=is.read(buffer)) != -1){
    
    
            sos.write(buffer,0,len);
        }
        sos.close();
        is.close();

    }

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

运行tomcat,输入http://localhost:8080/FileUpload/fileList,即可

猜你喜欢

转载自blog.csdn.net/weixin_39615182/article/details/113914998