简体   繁体   中英

How to insert multiple files into database, using Java Servlet 3.1

once again I need your help. I am trying to insert multiple files into DB table. I managed to insert 1 file - 1 row in the DB table, however I do not know how to do it for multiple files - multiple rows, in one request.

This is the part of my Servlet where I get the file from the html input:

InputStream otherFileInputStream = null;            
Part otherFilesPart = request.getPart("other_files");

if (otherFilesPart != null && otherFilesPart.getSize() != 0) {
    otherFileInputStream = otherFilesPart.getInputStream();                
}

And this is the method that I use for inserting the file into the database:

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;
}

When a user uploads 2 or 3 files, there should be 2-3 rows with the files uploaded? Bear in mind, that I do can not use Apache Commons for uploading files. The main idea is: In my website I have 2 different input type file multiple fields, which are corresponding to 2 different DB tables.

Use a loop inside your transaction essentially like this:

 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

Don't forget exception handling (ommitted for clarity)!

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM