• 文件的上传与下载



    一、 实验目的:

    掌握Servlet的HttpServletRequest对文件上传的支持;
    能够理解文件上传的原理,掌握文件上传与下载的步骤

    二、实验要求:

    1. 基于Servlet的文件上传。
    2. 文件的下载。
    3. 熟练使用MYEclipse开发

    三、实验内容:

    1、单文件上传

    uploadHttpOne.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java"  pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
        <title>HttpServletResquest对文件上传的支持</title>
        <meta charset="UTF-8">
    </head>
    <body>
    <form action="uploadHttpOneServlst" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>文件描述:</td>
                <td><input type="text" name="filediscription"></td>
            </tr>
            <tr>
                <td>请选择文件:</td>
                <td><input type="file" name="resPath"></td>
    
            </tr>
            <tr>
                <td align="right"><input type="reset" value="重填"></td>
                <td><input type="submit" value="上传"></td>
            </tr>
        </table>
    </form>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    UploadHttpOneServlst.java

    package servlet;
    
    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.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    @MultipartConfig(maxFileSize = 10 * 1024 * 1024)
    @WebServlet("/uploadHttpOneServlst")
    public class UploadHttpOneServlst extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            request.setCharacterEncoding("UTF-8");
            Part part = request.getPart("resPath");
            String filediscription = request.getParameter("filediscription");
            out.println("输入的文件描述:" + filediscription + "
    "
    ); File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles")); if (!uploadFileDir.exists()) { uploadFileDir.mkdir(); } String oldName = MyUtil.getFileName(part); out.println("上传文件的原始名:" + oldName + "
    "
    ); out.println("上传文件的大小:" + part.getSize() + "
    "
    ); if (oldName != null) { part.write(uploadFileDir + File.separator + oldName); } out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
    "
    ); } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    MyUtil.java

    package servlet;
    
    import javax.servlet.http.Part;
    
    public class MyUtil {
        public static String getFileName(Part part) {
            if (part == null)
                return null;
            String fileName = part.getHeader("content-disposition");
            if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
                return null;
            return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    运行结果:
    在这里插入图片描述
    在这里插入图片描述

    2、多文件上传

    UploadHttpMultiServlst.java

    package servlet;
    
    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.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Collection;
    
    @MultipartConfig
    @WebServlet("/uploadHttpMultiServlst")
    public class UploadHttpMultiServlst extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            request.setCharacterEncoding("UTF-8");
            String filediscription1 = request.getParameter("filediscription1");
            out.println("输入的文件1描述:" + filediscription1 + "
    "
    ); String filediscription2 = request.getParameter("filediscription2"); out.println("输入的文件2描述:" + filediscription2 + "
    "
    ); File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles")); if (!uploadFileDir.exists()) { uploadFileDir.mkdir(); } Collection<Part> parts = request.getParts(); for (Part part : parts) { if (part == null || !part.getName().contains("resPat")) { continue; } String oldName = MyUtil.getFileName(part); out.println("上传文件的原始名:" + oldName + "
    "
    ); out.println("上传文件的大小:" + part.getSize() + "
    "
    ); if (oldName != null) { part.write(uploadFileDir + File.separator + oldName); } out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
    "
    ); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    MyUtil.java

    package servlet;
    
    import javax.servlet.http.Part;
    
    public class MyUtil {
        public static String getFileName(Part part) {
            if (part == null)
                return null;
            String fileName = part.getHeader("content-disposition");
            if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
                return null;
            return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    UploadHttpMultiServlst.jsp

    <%@ page contentType="text/html;charset=UTF-8" 
    language="java" pageEncoding="utf-8" %>
    <!DOCTYPE html>
    <html>
    <head>
        <title>HttpServletResquest对文件上传的支持</title>
        <meta charset="UTF-8">
    </head>
    <body>
    <form action="uploadHttpMultiServlst" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>文件1描述:</td>
                <td><input type="text" name="filediscription1"></td>
            </tr>
            <tr>
                <td>请选择文件1</td>
                <td><input type="file" name="resPath1"></td>
    
            </tr>
            <tr>
                <td>文件2描述:</td>
                <td><input type="text" name="filediscription2"></td>
            </tr>
            <tr>
                <td>请选择文件2</td>
                <td><input type="file" name="resPath2"></td>
    
            </tr>
            <tr>
                <td align="right"><input type="reset" value="重填"></td>
                <td><input type="submit" value="上传"></td>
            </tr>
        </table>
    </form>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    运行结果:
    在这里插入图片描述
    在这里插入图片描述

    3、上传文件的大小限定

    对多文件上传实例文件大小进行限定!
    仅仅在UploadHttpMultiServlst.Java中加上限制条件——@MultipartConfig(maxFileSize = 10 * 1024 * 1024)//设置上传文件的最大值为10MB,其他代码不用变!
    UploadHttpMultiServlst.Java

    package servlet;
    
    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.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Collection;
    
    @MultipartConfig(maxFileSize = 10 * 1024 * 1024)//设置上传文件的最大值为10MB
    @WebServlet("/uploadHttpMultiServlst")
    public class UploadHttpMultiServlst extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            request.setCharacterEncoding("UTF-8");
            String filediscription1 = request.getParameter("filediscription1");
            out.println("输入的文件1描述:" + filediscription1 + "
    "
    ); String filediscription2 = request.getParameter("filediscription2"); out.println("输入的文件2描述:" + filediscription2 + "
    "
    ); File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles")); if (!uploadFileDir.exists()) { uploadFileDir.mkdir(); } Collection<Part> parts = request.getParts(); for (Part part : parts) { if (part == null || !part.getName().contains("resPat")) { continue; } String oldName = MyUtil.getFileName(part); out.println("上传文件的原始名:" + oldName + "
    "
    ); out.println("上传文件的大小:" + part.getSize() + "
    "
    ); if (oldName != null) { part.write(uploadFileDir + File.separator + oldName); } out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
    "
    ); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    运行结果:
    当其中一个文件大小大于10MB时,无法上传文件数据:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    当文件小于10MB时,能够正常上传:
    在这里插入图片描述
    在这里插入图片描述

    4、实现文件的下载功能,并解决下载乱码问题

    实验代码和运行结果如下:
    导包:在这里插入图片描述
    ShowDownServlet.java

    package servlet;
    
    import javax.servlet.RequestDispatcher;
    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;
    
    @WebServlet("/showDownServlet")
    public class ShowDownServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //指定从服务器uploadFiles目录中下载文件
            File downLoadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
            //获得目录中的文件
            File[] list = downLoadFileDir.listFiles();
            request.setAttribute("fileList", list);
            RequestDispatcher dis = request.getRequestDispatcher("showInfo.jsp");
            dis.forward(request, response);
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    MyUtil.java

    package servlet;
    
    import javax.servlet.http.Part;
    import java.io.UnsupportedEncodingException;
    
    public class MyUtil {
        public static String getFileName(Part part) {
            if (part == null)
                return null;
            String fileName = part.getHeader("content-disposition");
            if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
                return null;
            return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
        }
    
        //处理乱码问题
        public static String toUTF8String(String str) {
            StringBuffer sb = new StringBuffer();
            int len = str.length();
            for (int i = 0; i < len; i++) {
                char c = str.charAt(i);
                if (c >= 0 && c <= 255) {
                    sb.append(c);
                } else {
                    byte b[];
                    try {
                        b = Character.toString(c).getBytes("UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        b = null;
                    }
                    for (int j = 0; j < b.length; j++) {
                        int k = b[j];
                        if (k < 0) {
                            k &= 255;
                        }
                        sb.append("&" + Integer.toHexString(k).toUpperCase());
                    }
                }
            }
            return sb.toString();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    DownloadServlet.java

    package servlet;
    
    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;
    
    @WebServlet("/downloadServlet")
    public class DownloadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            File downLoadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
            String aFileName = null;
            FileInputStream in = null;
            ServletOutputStream out = null;
            try {
                aFileName = request.getParameter("resPath");
                response.setHeader("Content-Type", "application/x-msdownload");
                response.setHeader("Content-Dissposition", "attachment;filename=" + MyUtil.toUTF8String(aFileName));
                in = new FileInputStream(downLoadFileDir + File.separator + aFileName);
                out = response.getOutputStream();
                out.flush();
                int aRead = 0;
                byte b[] = new byte[1024];
                while ((aRead = in.read(b)) != -1 & in != null) {
                    out.write(b, 0, aRead);
                }
                out.flush();
                in.close();
                out.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    showInfo.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html>
    <head>
        <title>显示下载文件</title>
        <meta charset="UTF-8">
    </head>
    <body>
    <form action="uploadHttpMultiServlst" method="post" enctype="multipart/form-data">
        <table border="1">
            <tr bgcolor="#90ee90">
                <th>文件名称</th>
                <th>下载课件</th>
            </tr>
            <c:forEach var="afile" items="${fileList}">
                <tr>
                    <td>${afile.name}</td>
                    <td align="center"><a href="downloadServlet?resPath=${afile.name}"
                                          style="text-decoration: yellow">下载</a></td>
                </tr>
            </c:forEach>
        </table>
    </form>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    运行结果:
    在这里插入图片描述

  • 相关阅读:
    [安卓APP毕业设计源码]精品基于Uniapp+SSM实现的酒品移动电商平台app[包运行成功]
    pytorch使用LSTMCell层定义LSTM网络结构
    第三章变量
    缓存更新策略(旁路更新策略)
    DevEco Studio如何安装中文插件
    微信开发者工具如何使用?使用注意事项
    openlayers6 解决调用百度地图之各种问题
    5G智能网关如何解决城市停车痛点难点
    一种利用合法工具渗透的新型方法
    九泰智库 | 医械周刊- Vol.23
  • 原文地址:https://blog.csdn.net/qq_58251465/article/details/128148562