我正在尝试使用以下代码将图像上传到数据库,
MyJsp.jsp
<form action="ImageUploadToDB" method="post" enctype="multipart/form-data">
<div>
<img alt="Image1" id="Image11" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files11" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image2" id="Image12" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files12" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image3" id="Image13" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files13" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image4" id="Image14" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files14" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image5" id="Image15" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files15" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
</div>
</form>
我使用下面的servlet插入上面表格中的所有上传图片,
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.put(item.getName(), item.getInputStream());
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
如果我上传如images1.jpg,images2.jpg,images3.jpg,images4.jpg,images5.jpg那么我的输出是:
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
但是,如果我上传如images1.jpg,images2.jpg,images1.jpg,images4.jpg,images2.jpg那么我的输出是:
inserted successfully:
inserted successfully:
inserted successfully:
当我检查我的数据库时,只有image1.jpg,image2.jpg,image4.jpg。我不知道为什么同样的图像名称没有插入数据库。
有人告诉我哪里错了吗?
更新: 这是针对Mr.Keval的回答
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
int count2 =5;
for (int
k=0;k<5;k++) {
System.out.println("for successfully:");
String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, clas);
statement.setString(2, subject);
statement.setString(3, uid);
System.out.println("Qimg name is:"+listGet.get(k));
statement.setString(4, listGet.get(k));
System.out.println("Qimg is:"+fileMap.values().toArray()[k]);
Object bb = fileMap.values().toArray()[k];
// System.out.println("Qimg is:"+listGet2.get(listgetcount));
// System.out.println("finallyyyy:"+fileMap.get("files1"));
statement.setBinaryStream(5, (InputStream) bb);
// System.out.println("Aimg name is:"+listGet.get(count2));
statement.setString(6, listGet.get(count2));
//System.out.println("Aimg is:"+fileMap.values().toArray()[count2]);
Object bb2 = fileMap.values().toArray()[count2];
//System.out.println("Qimg is:"+fileMap.get("files2"));
//String getval2 = listGet2.get(count2);
statement.setBinaryStream(7, (InputStream) bb2);
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
count2=count2+1;
}
如果我上传相同的图片,则会显示
for successfully:
Qimg name is:image1.jpg
Qimg is:java.io.FileInputStream@f747c0
inserted successfully:
for successfully:
Qimg name is:image4.jpg
Qimg is:java.io.FileInputStream@fd4f30
inserted successfully:
for successfully:
Qimg name is:image5.jpg
Qimg is:java.io.FileInputStream@1b654b9
inserted successfully:
for successfully:
Qimg name is:image7.jpg
Qimg is:java.io.FileInputStream@1303c07
inserted successfully:
for successfully:
Qimg name is:image9.jpg
Qimg is:java.io.FileInputStream@110b3f6
java.lang.ArrayIndexOutOfBoundsException: 9
答案 0 :(得分:1)
由于您使用LinkedHashMap
将文件名作为键,因此当您添加两个相同名称的文件(两个具有相同键的条目)时,后者将替换前者。这导致替换具有重复名称的条目。考虑使用包含文件名的类(您创建的)的ArrayList以及InputStream
来存储此数据。
编辑:我的代码建议(未经测试)
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
ArrayList<FileWithStream> fileMap = new ArrayList<FileWithStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.add(new FileWithStream(item.getName(), item.getInputStream()));
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
for (FileWithStream file : fileMap) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, file.getStream());
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
有一个类:
public class FileWithStream {
private String name;
private InputStream stream;
public FileWithStream(String name, InputStream stream) {
this.name = name;
this.stream = stream;
}
public String getName() {
return name;
}
public InputStream getStream() {
return stream;
}
}
答案 1 :(得分:1)
将值放在地图
中...
fileMap.put(item.getName(),item.getInputStream());
...
您已将“文件名称”保留为关键字,而地图仅保留最后添加的值,以防重复键。
所以,我建议你用一个唯一的密钥替换你的文件名。
答案 2 :(得分:1)
您需要为每个图像提供唯一的图像名称其他明智的图像具有相同名称将覆盖地图中旧图像的值,因为键在地图中是唯一的
fileMap.put(item.getName(), item.getInputStream());
一种解决方案是,您可以使用文件名附加当前时间以使其唯一
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
答案 3 :(得分:-1)
最后我使用下面的代码得到答案,
Connection con1 =null;
Statement stmt=null;
int GetUniqueId=0;
System.out.println("Entered successfully 1:");
try
{
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
String sql1 ="select contact_id from contacts order by contact_id desc limit 1" ;
stmt = con1.createStatement();
ResultSet rst = stmt.executeQuery(sql1);
if(rst.next())
{
//String newone = rst.getString("contact_id");
GetUniqueId = Integer.parseInt(rst.getString("AutoIncrementValue"));
System.out.println("Ifffffffffffff"+GetUniqueId);
}
else
{
GetUniqueId = 0;
System.out.println("elseeeeeeeeeeee"+GetUniqueId);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
// item.getName() - gives file name
GetUniqueId = GetUniqueId+1;
String getfirst = item.getName();
String [] get = getfirst.split("\\.");
System.out.println("splited :"+get[0]);
System.out.println("splited :"+get[1]);
getchange = get[0];
getchange = getchange+""+ GetUniqueId;
String addjpg =getchange+"."+get[1];
System.out.println("splited finally :"+addjpg);
fileMap.put(addjpg, item.getInputStream());
listGetImgName.add(addjpg);
}
}
}
}
现在工作正常。感谢Mr.Keval和Mr.colavitam