tomcat实现一个简单的文件服务器,上传下载删除功能
昵称
密码

tomcat实现一个简单的文件服务器,上传下载删除功能

fl0919
2021-05-15 / 0 评论 / 3,683 阅读 / 正在检测是否收录...
/

前端?就一个上传页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
</head>
<body>
<form action="uploadfile" method="post" enctype = "multipart/form-data">
    <input type="file" name="filename" id="" value=""/>
    <input type="submit" value="上传"/>
</form>

</body>
</html>

java部分上传的Servlet

package com.icis.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

@MultipartConfig
@WebServlet("/uploadfile")
public class Uploadservlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //定位前端传来的的文件
        Part file = request.getPart("filename");
        //获取文件名
        String filename = file.getSubmittedFileName();
        System.out.println(filename);
        //获取写入tomcat服务器资源下的路径
        ServletContext servletContext = this.getServletContext();
        //realPath是服务器路径
        String realPath = servletContext.getRealPath("/anyresources");
        //文件写入,/代表的是写入到realPath下的,将write括号内部
        //看成一个整体的文件名,但是遇到/就分开了,自由最后/后的名字会被作为文件名
        file.write(realPath + "/" + filename);
        //提示上传成功
        PrintWriter out = response.getWriter();
        out.println("<html><head>");
        out.println("<title>上传文件</title></head>");
        out.println("<body>");
        out.println("<h2>淇宝用户,上传成功!</h2>");
        out.println("</body></html>");

    }

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

首页的Servlet,前端页面用StringBuilder拼的

package com.icis.servlet;

import org.junit.Test;

import javax.servlet.ServletContext;
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.io.PrintWriter;

@WebServlet("/filesindex")

public class filesIndexServlet extends HttpServlet {
    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        StringBuilder stringBuilder = new StringBuilder();
        //拼入前端固定页面
        stringBuilder.append("<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<meta charset=\"utf-8\">\n" +
                "\t\t<title></title>\n" +
                "\t\t<meta charset=\"utf-8\">\n" +
                "\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                "\t\t<title></title>\n" +
                "\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"./css/bootstrap.min.css\" />\n" +
                "\t\t<script src=\"js/jquery-3.2.1.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n" +
                "\t\t<script src=\"js/bootstrap.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n" +
                "\t</head>\n" +
                "\t<body>\n" +
                "\t\t<div class=\"container-fluid\" style=\"background-color: #1ccad9;\">\n" +
                "\t\t\t<h1 align=\"center\">文件系统</h1>\n" +
                "\t\t</div>\n" +
                "\t\t<div class=\"container\">\n" +
                "\t\t\t<table border=\"\" cellspacing=\"\" cellpadding=\"\" class=\"table\">\n" +
                "\t\t\t\t<tr><th>资源列表</th></tr>\n" +
                "\t\t\t\t<tr><td>文件名称</td><td>在线查看</td><td>下载</td><td>删除</td></tr>");

        //2.1找到文件服务器路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/anyresources");
        File file = new File(realPath);
        String[] list = file.list();
        for (String s : list) {
            stringBuilder.append("\t\t\t\t<tr><td>");
            //拼上文件名
            stringBuilder.append(s);

            //查看的文件名
            if (s.contains("jpg")||s.contains("png")){
                stringBuilder.append("\t<td><a href=\"checkfile?picname=");
                stringBuilder.append(s);

                stringBuilder.append("\">查看图片</a></td>");
            }
            else {
                stringBuilder.append("\t<td>无法查看</td>");

            }
            //stringBuilder.append("<td>在线查看</td><td><a href=\"downloadservlet?filename=");
            stringBuilder.append("<td><a href=\"downloadservlet?filename=");

            stringBuilder.append(s);
            stringBuilder.append("\">下载</a></td><td>删除</td></tr>");


        }

        //拼上前端尾部
        stringBuilder.append("</table>\n" +
                "\t\t</div>\n" +
                "\t</body>\n" +
                "</html>\n");

        //最后统一写
        writer.write(stringBuilder.toString());


    }

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

在线查看页面,也是用StringBuilder拼的 😊

package com.icis.servlet;

import javax.servlet.ServletContext;
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.io.PrintWriter;

@WebServlet("/checkfile")
public class CheckfileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String picname = request.getParameter("picname");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"utf-8\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                "    <title></title>\n" +
                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"./css/bootstrap.min.css\"/>\n" +
                "    <script src=\"js/jquery-3.2.1.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n" +
                "    <script src=\"js/bootstrap.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n" +
                "\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"container\" style=\"background-color: white; height: 50px\"></div>\n" +
                "<div class=\"container\" style=\"background-color: white;\">\n" +
                "\n" +
                "    <img src=\"downloadservlet?filename=");
        stringBuilder.append(picname);

        //拼上前端尾部
        stringBuilder.append("\" class=\"img-responsive\">\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>");
        writer.write(stringBuilder.toString());

    }

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

下载功能的Servlet需要一个处理下载的Servlet工具

package com.icis.servlet;

import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class DownLoadUtils {

    public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}

处理下载请求的Servlet

package com.icis.servlet;

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.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

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

        //1.获取请求参数,文件名称
        String filename = request.getParameter("filename");
        //2.使用字节输入流加载文件进内存
        //2.1找到文件服务器路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/anyresources/" + filename);
        //2.2用字节流关联
        FileInputStream fis = new FileInputStream(realPath);

        //3.设置response的响应头
        //3.1设置响应头类型:content-type
        String mimeType = servletContext.getMimeType(filename);//获取文件的mime类型
        response.setHeader("content-type",mimeType);
        //3.2设置响应头打开方式:content-disposition

        //解决中文文件名问题
        //1.获取user-agent请求头、
        String agent = request.getHeader("user-agent");
        //2.使用工具类方法编码文件名即可
        filename = DownLoadUtils.getFileName(agent, filename);

        response.setHeader("content-disposition","attachment;filename="+filename);
        //4.将输入流的数据写出到输出流中
        ServletOutputStream sos = response.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while((len = fis.read(buff)) != -1){
            sos.write(buff,0,len);
        }

        fis.close();


    }

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

删除的Servlet



import javax.servlet.ServletContext;
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.io.PrintWriter;

@WebServlet("/deletefile")
public class DeletefileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String filename = request.getParameter("filename");

        //获取写入tomcat服务器资源下的路径
        ServletContext servletContext = this.getServletContext();
        //realPath是服务器路径
        String realPath = servletContext.getRealPath("/anyresources");
        //获得文件服务器下的文件名
        String getfilename = realPath + "/" + filename;
        File file = new File(getfilename);
        //删除文件
        file.delete();
        PrintWriter writer = response.getWriter();
        //写入一个返回首页的页面
        String indexhtml="<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>删除成功</title>\n" +
                "    <script type=\"text/javascript\">\n" +
                "        self.location='filesindex';\n" +
                "    </script>\n" +
                "</head>\n" +
                "<body>\n" +
                "</body>\n" +
                "</html>";
        //写入
        writer.write(indexhtml);


    }

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

1,668

评论

博主关闭了所有页面的评论