大佬教程收集整理的这篇文章主要介绍了如何使用 Java Servlet 3.1 将多个文件插入数据库,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我再次需要你的帮助。我正在尝试将多个文件插入到 DB 表中。我设法在数据库表中插入 1 个文件 - 1 行,但是我不知道如何在一个请求中为多个文件 - 多行执行此操作。
这是我从 HTML 输入获取文件的 Servlet 的一部分:
inputStream otherfileinputStream = null;
Part otherfilesPart = request.getPart("other_files");
if (otherfilesPart != null && otherfilesPart.getSize() != 0) {
otherfileinputStream = otherfilesPart.geTinputStream();
}
这是我用来将文件插入数据库的方法:
private int addOtherfiles(long personID,int userID) throws sqlException {
int res = 0;
con.setautoCommit(true);
String sql = "insert into person_other_files(person_fk,other_files,user_fk) values (?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
if (otherfileinputStream != null) {
ps.setLong(1,personID);
ps.setBlob(2,otherfileinputStream);
ps.seTint(3,userID);
ps.executeupdate();
ps.close();
}
return res;
}
当用户上传 2 或 3 个文件时,上传的文件应该有 2-3 行吗?请记住,我不能使用 Apache Commons 上传文件。主要思想是:在我的网站中,我有 2 个不同的输入类型文件 @H_837_17@multiple 字段,它们对应于 2 个不同的数据库表。
在您的交易中使用循环,本质上是这样的:
con.setAutoCommit(false); // enable transaction,turning off the auto-
// commit
String sql = "INSERT INTO person_other_files(person_fk,other_files,user_fk)
VALUES (?,?,?)";
for (String file : files) // "files" is your list of files
{
PreparedStatement ps = con.prepareStatement(sql);
Path filePath = Paths.get(filE);
byte[] bytes = Files.readAllBytes(filePath);
if (bytes != null)
{
ps.setLong(1,personId);
ps.setBlob(2,bytes);
ps.seTint(3,userId);
ps.executeupdate();
ps.close();
}
}
con.commit(); // commit transaction at the end
不要忘记异常处理(为清楚起见省略)!
问候
以上是大佬教程为你收集整理的如何使用 Java Servlet 3.1 将多个文件插入数据库全部内容,希望文章能够帮你解决如何使用 Java Servlet 3.1 将多个文件插入数据库所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。