You need to enable JavaScript to run this app. 如何使用Java Servlet 3.1将多个上传文件批量插入数据库
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java Servlet 3.1将多个上传文件批量插入数据库

实现方案(基于Servlet 3.1+ 原生API,无需第三方组件)

1. 前端配置确认

确认两个带multiple属性的文件输入框name属性唯一,比如对应两个表分别命名为other_files和biz_files,方便后端按name分组获取文件。

2. 后端批量获取同组文件

原生Servlet的request.getPart()仅能获取同name下的第一个文件,要获取全部同组文件,需遍历request.getParts()按name筛选:

// 筛选name为other_files的所有文件Part
List<Part> otherFileParts = new ArrayList<>();
// 筛选name为biz_files的所有文件Part(对应第二个表)
List<Part> bizFileParts = new ArrayList<>();

for (Part part : request.getParts()) {
    if ("other_files".equals(part.getName()) && part.getSize() > 0) {
        otherFileParts.add(part);
    } else if ("biz_files".equals(part.getName()) && part.getSize() > 0) {
        bizFileParts.add(part);
    }
}

3. 改造数据库插入方法

原方法依赖全局的InputStream变量,无法支持多文件循环调用,需改为参数传入流,同时优化事务逻辑保证数据一致性:

// 插入person_other_files表的方法
private int addOtherFile(long personId, int userId, InputStream fileStream, Connection con) throws SQLException {
    String sql = "insert into person_other_files(person_fk, other_files, user_fk) values (?, ?, ?)";
    // 用try-with-resources自动关闭PreparedStatement
    try (PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setLong(1, personId);        
        ps.setBlob(2, fileStream);
        ps.setInt(3, userId);
        return ps.executeUpdate();
    }
}

// 第二个表的插入方法可参考上面实现,修改SQL和入参即可

4. 循环插入多条记录

关闭自动提交,所有文件插入成功后再提交事务,避免脏数据:

Connection con = // 你的数据库连接获取逻辑
try {
    con.setAutoCommit(false);
    // 插入第一组文件到对应表
    for (Part part : otherFileParts) {
        try (InputStream is = part.getInputStream()) {
            addOtherFile(personId, userId, is, con);
        }
    }
    // 插入第二组文件到另一个表,调用对应插入方法即可
    for (Part part : bizFileParts) {
        try (InputStream is = part.getInputStream()) {
            addBizFile(xxxId, userId, is, con); // 第二个表的插入方法
        }
    }
    // 全部插入成功提交事务
    con.commit();
} catch (Exception e) {
    // 出现异常回滚
    con.rollback();
    throw new RuntimeException("文件插入失败", e);
} finally {
    con.setAutoCommit(true);
    con.close();
}

注意事项

  • 每个文件Part对应独立的InputStream,不要复用流对象,避免插入数据异常
  • 所有可关闭资源用try-with-resources包裹,自动释放避免内存泄漏
  • 如果不需要严格的事务一致性,也可以保留自动提交逻辑,按单个文件逐一插入

内容的提问来源于stack exchange,提问作者NewJavaEnthusiast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 14:48:01