0

I like this simple code from ajajava.com on how to read and traverse a ZIP file.

ZipFile zipFile = new ZipFile("test.zip");
Enumeration<?> enu = zipFile.entries();
while (enu.hasMoreElements()) {
    ZipEntry zipEntry = (ZipEntry) enu.nextElement();
    String name = zipEntry.getName();
    long size = zipEntry.getSize();
    long compressedSize = zipEntry.getCompressedSize();
    System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", name, size, compressedSize);

However, my problem is that the ZIP file in my application is uploaded via HTML so I can't pass a string or a File object to the ZipFile object. My ZIP file is of type Part. and if I do this:

ZipFile zipFile = new ZipFile((File) uploadedZIP);

I receive this run time error:

java.lang.ClassCastException: org.apache.catalina.fileupload.PartItem cannot be cast to java.io.File

My applications allows the user to:

  1. upload a single image - works fine

    2.upload a ZIP file of many images - have a problem with

This is my HTML:

<%-- 
    Document   : index
    Created on : Jul 26, 2016, 1:13:25 PM
    Author     : bnbih
--%>
<%@page import = "java.sql.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="uploadServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>Single Student Portrait Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>

                <tr>
                    <td>ZIP file - Student Portrait Photos: </td>
                    <td><input type="file" name="zip" size="50"/></td>
                </tr>

                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

This is the Java code:

@WebServlet(urlPatterns = {"/uploadServlet"})
@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {

     // database connection settings
    private String dbURL = "jdbc:mysql://db_ip:3306/db_name";
    private String dbUser = "root";
    private String dbPass = "***";

    private List<Part> uploadedParts;
    private Part singleFile;
    private Part uploadedZIP;


    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String message = null;
        InputStream inputstream = null;//input stream of the single uploaded photo
        ZipInputStream zipinputstream = null;

        //get uploaded items
        uploadedParts = (List<Part>) request.getParts();

        singleFile = uploadedParts.get(0);//single image file
        uploadedZIP = uploadedParts.get(1);//zip file

        if(singleFile.getSize() != 0){
       //print out file info for debugging
       System.out.println(singleFile.getName());
       System.out.println(singleFile.getSize());
       System.out.println(singleFile.getContentType());
       //get the file 
       inputstream = singleFile.getInputStream();  
        }

        if(uploadedZIP.getSize() != 0){
        //print out file info for debugging
       System.out.println(uploadedZIP.getName());
       //System.out.println(zipFile.getSize);
       //System.out.println(zipFile.getContentType());
       //get the file 

       ZipFile zipFile = new ZipFile((File) uploadedZIP);
       Enumeration<?> enu = zipFile.entries();

       while(enu.hasMoreElements()){
       ZipEntry zipEntry = (ZipEntry) enu.nextElement();

       String name = zipEntry.getName();
       long size = zipEntry.getSize();
       long compressedSize = zipEntry.getCompressedSize();
       System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", 
    name, size, compressedSize);

       }

        }
        Connection con = null;


        try{
        //connect to the database
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        con = DriverManager.getConnection(dbURL, dbUser, dbPass);

        //construct sql statement
        String sql = "INSERT INTO StudentInfo (img, student) values (?,?)";
        PreparedStatement statement = con.prepareStatement(sql);

        if(inputstream != null){
        //fetches input stream of the upload file for the blob column
        statement.setBlob(1, inputstream);
        statement.setString(2, getFileName(singleFile));
        }

        else{message = "No file was uploaded";}
        //sends the statement to the database server
        int row = statement.executeUpdate();

        if(row > 0)
                message = "Student image uploaded successfully";
        else
                message = "the image was not inserted into the database";

        }catch(SQLException ex){
        message = "Something went wrong!! see below \n" + ex.getMessage() + getFileName(singleFile);
        }finally{
        if(con != null){
        //close db connection
        try{
        con.close();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }

 //sets the message in request scope

 request.setAttribute("Message", message);

 // forwards to the message page
 getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);

 }
}
Seif
  • 566
  • 2
  • 10
  • 21
  • 1
    1) Please don't use `ZipFile`, it's a nasty nasty API - use [Zip `FileSystemProvider`](https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html). 2) A multipart request containing an uploaded file would normally be first written to a temp location on disk - what if the file is 300MB, do you really want that in RAM? Take a look at [Common FileUpload](https://commons.apache.org/proper/commons-fileupload/) or the native API on [Servlet 3.0](https://docs.oracle.com/javaee/6/tutorial/doc/glrbb.html). – Boris the Spider Aug 11 '16 at 08:05
  • 1
    3) **never store request state in servlet instance variables**. Servlets are multithreaded and reused for multiple requests _at the same time_, if you have two or more simultaneous requests your code will blow up in spectacular manner. At seemingly random. – Boris the Spider Aug 11 '16 at 08:08
  • Thanks a lot. However, I have similar problem which is that I need to pass a path string as in: Path zipfile = Paths.get("/codeSamples/zipfs/zipfstest.zip"); How do I do that when the file is uploaded via HTML? Thanks. – Seif Aug 11 '16 at 08:19
  • 1
    Did you bother to read the links? I think not... – Boris the Spider Aug 11 '16 at 09:39
  • I did but how do I traverse through the individual physical files to store them in MySQL.http://stackoverflow.com/questions/38894464/how-to-traverse-a-zip-file-in-java-using-zip-file-system-provider – Seif Aug 11 '16 at 11:21
  • Don't store files in a database. It's slow and inefficient. Store files on the filesystem and store the paths in the database. – Boris the Spider Aug 11 '16 at 11:22

0 Answers0