index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
    <form action="fileUpload.jsp" method="post" enctype="multipart/form-data">
        <label>文件夹名称:</label>
        <input type="text" name="folderName" value="zhangsan"><br>
        <label>请选择文件:</label>
        <input type="file" name="file"><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

fileUpload.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.util.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
    <%
        // 设置上传文件的保存目录
        String folderName = request.getParameter("folderName");
        String savePath = getServletContext().getRealPath("/uploadFolder/" + folderName);

        // 检查上传文件的保存目录是否存在
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath + "目录不存在,需要创建");
            // 创建目录
            file.mkdir();
        }

        // 文件上传的处理
        // 1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 2、创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
        // 3、判断提交上来的数据是否是上传表单的数据
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 按照传统方式获取数据
            return;
        }

        // 设置上传单个文件的大小的最大值,目前设置为2MB
        upload.setFileSizeMax(2 * 1024 * 1024);

        try {
            // 4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,
            // 每一个FileItem对应一个Form表单的输入项
            List<FileItem> list = upload.parseRequest(request);
            for (FileItem item : list) {
                // 如果fileitem中封装的是普通输入项的数据
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    // 解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");
                    // value = new String(value.getBytes("iso8859-1"), "UTF-8");
                    System.out.println(name + "=" + value);
                } else {// 如果fileitem中封装的是上传文件
                    // 得到上传的文件名称,
                    String fileName = item.getName();
                    System.out.println("上传的文件名称:" + fileName);
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    // 获取上传文件的扩展名
                    int index = fileName.lastIndexOf(".");
                    String nameExt = fileName.substring(index + 1).toLowerCase();
                    if (nameExt.equals("jsp")) {
                        out.println("<script>alert('不允许上传jsp文件!');window.location.href='index.jsp'</script>");
                        return;
                    }
                    if (nameExt.equals("jpg") || nameExt.equals("jpeg") || nameExt.equals("png")
                            || nameExt.equals("gif") || nameExt.equals("bmp")) {
                        // 如果是图片文件,则显示图片
                        InputStream in = item.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        while ((len = in.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        byte[] data = outStream.toByteArray();
                        String base64 = Base64.getEncoder().encodeToString(data);
                        out.println("<img src='data:image/" + nameExt + ";base64," + base64 + "' style='max-width:300px;max-height:300px;'>");
                        in.close();
                    }
                    // 获取item中的上传文件的输入流
                    InputStream in = item.getInputStream();
                    // 创建一个文件输出流
                    FileOutputStream out = new FileOutputStream(savePath + "\\" + fileName);
                    // 创建一个缓冲区
                    byte buffer[] = new byte[1024];
                    // 判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    // 循环将输入流读入到缓冲区当中
                    while ((len = in.read(buffer)) > 0) {
                        // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + fileName)当中
                        out.write(buffer, 0, len);
                    }
                    // 关闭输入流
                    in.close();
                    // 关闭输出流
                    out.close();
                    // 删除处理文件上传时生成的临时文件
                    item.delete();
                    out.println("文件上传成功!");
                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    %>
    <br>
    <a href="index.jsp">返回上传页面</a>
</body>
</html>
练习案例ch45ex_uploadLimited有限制的上传参考案例ch45_fileUpload文件上传完成练习案例ch45ex_uploadLimited有限制的上传页面的测试效果如图4-11至4-14所示。要求:1创建Web项目ch45ex_uploadLimited将案例素材中的网页文件indexjsp和fileUploadjsp件复制到目录srcmainwebapp将2个jar包comm

原文地址: https://www.cveoy.top/t/topic/4m1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录