4

I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:

Servlet:

package Servlets;
import java.io.File;  
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.Iterator;   
import java.util.List;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileItemFactory;  
import org.apache.commons.fileupload.FileUploadException;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  

public class UploadServlet extends HttpServlet 
{  

private static final long serialVersionUID = 1L;

    @Override  
      protected void doPost(HttpServletRequest request, HttpServletResponse response)  
          throws ServletException, IOException 
          {  
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
            response.setContentType("text/html");  
            PrintWriter out = response.getWriter();  
            if (isMultipart) 
            {  
                // Create a factory for disk-based file items  
                FileItemFactory factory = new DiskFileItemFactory();  
                // Create a new file upload handler  
                ServletFileUpload upload = new ServletFileUpload(factory);  
                try 
                {  
                    // Parse the request  
                    List items = upload.parseRequest(request);  
                    Iterator iterator = items.iterator();  
                    while (iterator.hasNext()) 
                    {  
                        FileItem item = (FileItem) iterator.next();  
                        if (!item.isFormField())  
                        {  
                            String fileName = item.getName();      
                            String root = getServletContext().getRealPath("/");  
                            File path = new File(root + "/uploads");  
                            if (!path.exists())  
                            {  
                                boolean status = path.mkdirs();  
                            }  
                            File uploadedFile = new File(path + "/" + fileName);  
                            System.out.println(uploadedFile.getAbsolutePath());  
                        if(fileName!="")  
                            item.write(uploadedFile);  
                        else  
                        out.println("file not found");  
                        out.println("<h1>File Uploaded Successfully....:-)</h1>");  
                    }  
                    else  
                    {  
                        String abc = item.getString();  
                        out.println("<br><br><h1>"+abc+"</h1><br><br>");  
                    }  
                }  
            } 
            catch (FileUploadException e) 
            {  
            out.println(e);  
            } 
            catch (Exception e) 
            {  
            out.println(e);  
            }  
        }  
        else  
        {  
            out.println("Not Multipart");  
        }  
      }  
}

.JSP File:

<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
    <p><input type="file" name="dataFile" id="fileChooser" />&nbsp;
    <input type="submit" value="Upload" multiple="multiple" /></p>
</form>

I am looking for a way to upload multiple files instead of just one and show them in a list.

user3029610
  • 49
  • 1
  • 1
  • 2

7 Answers7

5

Check the FileUPload Using Servlet 3.0

It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.

just use below index.html

<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file"  name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>

Only change here is I have used multiple attribute for input type File

Dushyant Deshwal
  • 388
  • 4
  • 17
Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36
1

Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I changed it but, no dice. – user3029610 Nov 25 '13 at 01:48
  • It seems I'm repeating the same comment, but "no dice" gives absolutely no useful feedback as to what specifically is going wrong, and how one can help you. "As suggested, I changed the code like this: but I still cannot upload more than one file" is useful. Or "... but now even if I do upload more files, the serverside component finds only one of them." is useful. "no dice" is about as informative as "Doc, something's funny" when going to an emergency. – Amadan Nov 25 '13 at 01:54
  • @user3029610 do the change in the code of your question. – Kaushik Lele Jul 21 '15 at 12:56
1

i have upload multiple files using jsp /servlet. following is the code that i have used.

<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>

on the other hand server side. use following code.

    package com.abc..servlet;

import java.io.File;
---------
--------


/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.sendRedirect("../jsp/ErrorPage.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

            PrintWriter out = response.getWriter();
            HttpSession httpSession = request.getSession();
            String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

            String path1 =  filePathUpload;
            String filename = null;
            File path = null;
            FileItem item=null;


            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String FieldName = "";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                         item = (FileItem) iterator.next();

                            if (fieldname.equals("description")) {
                                description = item.getString();
                            }
                        }
                        if (!item.isFormField()) {
                            filename = item.getName();
                            path = new File(path1 + File.separator);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            /* START OF CODE FRO PRIVILEDGE*/

                            File uploadedFile = new File(path + Filename);  // for copy file
                            item.write(uploadedFile);
                            }
                        } else {
                            f1 = item.getName();
                        }

                    } // END OF WHILE 
                    response.sendRedirect("welcome.jsp");
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }   
    }

}
Mitul Maheshwari
  • 2,647
  • 4
  • 24
  • 38
0

images.jsp

choose files:

storeimages.java servlet

public class storeimages extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
                                                   IOException {

String sav_dir=""; //this will be a folder inside
        //directory
        PrintWriter out =response.getWriter();

        //if you want u can give this at run time
         sav_dir="6022"; //in my case folder name is 6022 
         //you can alse set this at dynamic

        int flag = 0;

        //now set the path
        //this is the path where my images are stored
        //now u can see the code
 String savepath="K:/imageupload"+File.separator +sav_dir;   

 File file = new File(savepath);

 if(!file.exists()){

     file.mkdir();
 }

 String filename="";

 List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
        toList());

for(Part filePart: fileParts){
    filename=Paths.get(filePart.getSubmittedFileName()).
    getFileName().toString();

    filePart.write(savepath+File.separator+filename);
    flag=1;


}
         if(flag==1){

             out.println("success");
         }

         else{

             out.println("try again");
         }

     //now save this and run the project
    }
}
s.nainwal
  • 21
  • 5
0

You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:

<input type="file" name="file" id="file" multiple/> 

This will let you choose multiple files at once. Good luck

Joe9008
  • 645
  • 7
  • 14
0

This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB. ** html/jsp ** .jsp file

<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
<a href="javascript:void(0);" class="remove_fields"  id="add_fields">Add</a>
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
 </div>

jquery validation

<script>
$(document).ready(function(){
    $('#add_fields').click( function(){
        add_inputs()
    });

    $(document).on('click', '.remove_fields', function() {
        $(this).closest('.record').remove();
    });
    function add_inputs(){
        var counter = parseInt($('#counter').val());
        var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input"><a href="javascript:void(0);" class="remove_fields">Remove</a></div>';
        $('#add_field_div').append(html);
        $('#counter').val( counter + 1 );
    }
    $('form#upload_form').on('submit', function(event) {
        //Add validation rule for dynamically generated name fields
    $('.upload_input').each(function() {
        $(this).rules("add", 
            {
                required: true,
                messages: {
                    required: "File is required",
                }
            });
    });

});
$("#upload_form").validate();


});
</script>

servlet

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//      KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();


        PrintWriter writer = response.getWriter();
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));

        if (!ServletFileUpload.isMultipartContent(request)) {
            writer.println("Fehler: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
        String message = null;
        InputStream inputStream = null;
        Connection dbConnection = null;

        String page = "";
        try {
            for (Part filePart : request.getParts()) {
                System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
                if (filePart != null && filePart.getSize() != 0) {
                    inputStream = filePart.getInputStream();

                    System.out.println("inputStream" + inputStream);
                     HttpSession session=request.getSession();  
                     session.setAttribute("username",request.getRemoteUser());  
                    Class.forName(properties.getProperty("driverClassName"));
                    dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
                    if (dbConnection != null) {

                            String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
                            PreparedStatement statement = dbConnection.prepareStatement(sql);

                            if (inputStream != null) {
                                statement.setString(1, getFileName(filePart));
                                statement.setLong(2, filePart.getSize());
                                statement.setBlob(3, inputStream);
                                statement.setString(4, filePart.getContentType());
                            }

                            Calendar calendar = Calendar.getInstance();
                            java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
                            statement.setDate(5, entryDate);
                            statement.setString(6, request.getRemoteUser());
                            //statement.setString(6, username);

                            int row = statement.executeUpdate();
                            if (row > 0) {
                                message = "Datei hochgeladen und in der Datenbank gespeichert";
                            }else {
                                message = "Fehler: Connection Problem";
                            }
                        }                   message = "Datei hochgeladen und in der Datenbank gespeichert";

                        }else {
                            page = "index.jsp";
                            System.out.println("cannot execute if condition");
                            message = "Das Upload-Feld darf nicht leer sein ";
                            RequestDispatcher dd = request.getRequestDispatcher(page);
                            dd.forward(request, response);
                            return;
                        }
                } 
            }catch (Exception exc) {
            page = "index.jsp";
            message = "Fehler: " + exc.getMessage();
            exc.printStackTrace();
        } finally {
            if (dbConnection != null) {
                try {
                    dbConnection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                page = "index.jsp";
                request.setAttribute("message", message);
                RequestDispatcher dd = request.getRequestDispatcher(page);
                dd.forward(request, response);
            }
        }
    }

    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

I hope people find it useful!!

-1

To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.

That is, use the below line multiple times:

<input type="file" name="dataFile" id="fileChooser" /><br><br>

Refer this link for details

I hope this helps.