java-web 文件上传so-easy

该博客详细介绍了如何在Java Web环境中实现文件上传功能,包括前端表单设置、后端Servlet处理、文件大小限制、文件名重复处理以及文件安全存储。使用了Apache的commons-fileupload和commons-io库来简化上传过程,并展示了如何监听上传进度。同时,文章强调了文件应存储在外界无法直接访问的位置,如WEB-INF文件夹下,确保安全性。
摘要由CSDN通过智能技术生成

文件上传

文件上传要求

  1. 文件类型限制
  2. 文件大小限制,服务器硬盘资源需要买的
  3. 文件上传后,文件名重复问题(解决,时间戳,uuid,md5)
  4. 文件上传后,应该放到外界访问不到的地方,如web-inf文件夹下

前端页面

<%--index.jsp--%>
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$upload-file$</title>
</head>
<body>

<%--index.jsp--%>
<%--通过白哦但上传文件
  get:上传文件大小有限制
  post:无限制
  --%>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
  上传用户:<input type="text" name="username"><br/>
  上传文件1:<input type="file" name="file1"><br/>
  上传文件2:<input type="file" name="file2"><br/>
  <p><input type="submit" value="提交"> | <input type="reset" name="重置"></p>
</form>

</body>
</html>

info.jsp

<%--
  Created by IntelliJ IDEA.
  User: Apple
  Date: 2021/12/14
  Time: 7:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

添加依赖

文件上传:

  • commons-io

  • commons-fileupload

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
</dependencies>

后台代码

package com.hopeful.servlet;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import sun.net.ProgressListener;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * FileServlet
 *
 * @author : yl
 * @version : [v1.0]
 * @createTime : [2021/12/14 7:41]
 */
public class FileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 判断上传文件是普通表单还是带文件的表单

        if (!ServletFileUpload.isMultipartContent(req)) {
            // 普通表单直接返回
            return;
        }
        // 创建上传文件的保存路径,建议保存在WEB-INF路径下,安全,用户无法直接访问上传的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        // 如果路径不存在,则创建文件
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        // 创建临时文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
        File file = new File(tmpPath);
        if (file.exists()) {
            file.mkdir();// 创建不存在的路径
        }

        // 处理上传的文件,一般都需要通过流来获取,我们可以用request.getInputStream(),原生态的文件上传流获取,十分麻烦
        // 我们建议使用Apache的文件上传组件来实现,common-fileupload,它需要commons-io组件

        // 1.创建DiskFileItemFactory对象,处理文件路径或大小限制
        DiskFileItemFactory factory = getDiskFileItemFactory(file);

        // 2.获取ServletFileUpload
        ServletFileUpload upload = getServletFileUpload(factory);

        // 3.处理上传文件
        // 把前端请求解析,封装成FileItem对象,需要从ServletFileUpload对象中获取
        try {
            String msg = uploaParseRequest(upload, req, uploadPath);
            if (!"上传成功".equals(msg)) {
                msg = "上传文件有误,请重新上传";
            }
            req.setAttribute("msg", msg);
            req.getRequestDispatcher("info.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.doPost(req, resp);
    }

    private String uploaParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws Exception {
        String msg = "";
        List<FileItem> fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                //普通表单处理
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                System.out.println(name + ":" + value);
            } else {
                // 处理上传文件
                String uploadFilename = fileItem.getName();
                System.out.println("上传的文件名:" + uploadFilename);
                if (uploadFilename.trim().equals("") || uploadFilename == null) {
                    continue;
                }

                // 获取上传文件的文件名或后缀名
                String fileName = uploadFilename.substring(uploadFilename.lastIndexOf("/") + 1);
                String fileExtName = uploadFilename.substring(uploadFilename.lastIndexOf(".") + 1);

                // 如果文件后缀名FileExtName不是我们需要的,就直接return,不处理,告诉用户文件类型不对
                System.out.println("文件信息【文件名: " + fileName + "---文件类型" + fileExtName + "】");

                // 使用UUID保证文件名唯一
                String uuidPath = UUID.randomUUID().toString();


                // 处理文件完毕
                // 文件真实的存放路径
                String realPath = uploadPath + "/" + uuidPath;
                // 给每一个文件创建一个对应的文件夹
                File realPathFile = new File(realPath);
                if (!realPathFile.exists()) {
                    realPathFile.mkdir();
                }

                // 获取文件上传流
                InputStream inputStream = fileItem.getInputStream();
                // 获取输出流
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
                // 创建缓冲区
                byte[] buffer = new byte[1024 * 1024];
                // 判断是否读取完毕
                int len = 0;
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                // 关闭流
                fos.close();
                inputStream.close();

                msg = "上传成功";
                fileItem.delete();
            }
        }

        return msg;

    }

    private ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 监听上传进度
        upload.setProgressListener(new ProgressListener() {
            // pBytesRead:已读取到文件大小  enctype="Multipart/form-data"
            // pContextLength: 文件大小
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead + ",进度:" + ((double) pBytesRead / pContentLength * 100) + "%");
            }
        });
        // 处理乱码问题
        upload.setHeaderEncoding("utf-8");
        // 设置单个文件最大值 1024 = 1kb * 1024 = 1M * 10 = 10M
        upload.setFileSizeMax(1024 * 1024 * 10);
        return upload;
    }

    private DiskFileItemFactory getDiskFileItemFactory(File file) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 通过工厂设置一个缓存区,当上传文件大于这个缓存区的时候,将他放到临时文件中
        factory.setSizeThreshold(1024 * 1024);  //缓存区大小为1m
        factory.setRepository(file); // 临时目录的保存目录,需要一个file
        return factory;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值