Multiple image upload using JSP

I  have written a code to upload the multiple images using jsp, but when I execute this code, it throws Corrupt form data: premature ending error.

Apache tomcat version :

Can anybody please help me to resolve this issue?

Html file

<html xmlns="">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <FORM action="upload_jsp.jsp" enctype="multipart/form-data" method="post">

   What files are you sending? <INPUT type="file" name="file[]" multiple >
   <INPUT type="submit" value="Send"> <INPUT type="reset">

JSP Code

<%@ page import="java.sql.*" %>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>

<%@ page import="" %>

<%@ page import="*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>

<%@ page import="com.oreilly.servlet.multipart.MultipartParser"%>
<%@ page import="com.oreilly.servlet.multipart.Part"%>
<%@ page import="com.oreilly.servlet.multipart.FilePart"%>

    String fileSavePath_upload_dir;
    String fileSavePath_upload_user_dir;
    String fileSavePath_sec_storage_user_dir;
    String user_name = "abc1234567890";
    String sec_storage_images_path = "C:\\Users\\gur29175\\Desktop";
    String UPLOAD_DIRECTORY = "Uploads";    
    String user_image_dir = user_name;

    File sourceFile;
    File destinationFile;    
    String resp = "";    
    int i = 1;
    int counter=0;    

    fileSavePath_upload_dir = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
    fileSavePath_upload_user_dir = fileSavePath_upload_dir + File.separator + user_image_dir;
    fileSavePath_sec_storage_user_dir = sec_storage_images_path + File.separator + user_name;

    if (!(new File(fileSavePath_upload_dir)).exists())
        (new File(fileSavePath_upload_dir)).mkdir();    // creates the directory if it does not exist        

    if (!(new File(fileSavePath_upload_user_dir)).exists())
        (new File(fileSavePath_upload_user_dir)).mkdir();    // creates the directory if it does not exist        

    if (!(new File(sec_storage_images_path)).exists())
        (new File(sec_storage_images_path)).mkdir();    // creates the directory if it does not exist        

    if (!(new File(fileSavePath_sec_storage_user_dir)).exists())
        (new File(fileSavePath_sec_storage_user_dir)).mkdir();    // creates the directory if it does not exist        

    resp += "<br>Here is information about uploaded files.<br>";
        MultipartParser parser = new MultipartParser(request, 1024*1024*1024);  /* file limit size of 1GB*/
        Part _part;
        while ((_part = parser.readNextPart()) != null)
            if (_part.isFile())
                FilePart fPart = (FilePart) _part;  // get some info about the file
                String name = fPart.getFileName();

                if (null != name)
                    long fileSize = fPart.writeTo(new File(fileSavePath_upload_user_dir));
                    resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";

                    sourceFile = new File(fileSavePath_upload_user_dir+"/"+user_name+"_"+counter+".png");
                }                 else
                    resp = "<br>The user did not upload a file for this part.";
        }// end while
    catch ( ioe)
        resp = ioe.getMessage();
byox deveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Are you and 
the same person?  
If not, then why is your code the same as posted at   
If yes, then why didn't you respond to my comment in your first question?
byox deveAuthor Commented:
sorry .I didn't know that my colleague has already posted the same question.. Actually We are working in same team.. and currently he is on leave.. I am seeing his code and facing that problem.. then I have posted that problem...In fact I recommended him to post your problem on this website..

But because he is on leave so don't wanted to disturb him to ask the status of problem..
I don't recommend the O'Reilly API.
I will post demonstration code using  Apache commons FileUpload  and also code using Servlet 3.1 API. You will have to decide which one to use in your project.  For convenience  and simplicity  manually create a folder named "fileUploads" in the root folder of your web app. For the same reasons, I use a JSP for the Apache commons demo.
<%@ page import="java.util.*,
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  out.print("Request content length is " + request.getContentLength() + "<br/>"); 
                  ServletFileUpload upload = new ServletFileUpload();
                  FileItemIterator iter = upload.getItemIterator(request);
                  FileItemStream item = null;
                  String name = "";
                  InputStream stream = null;
                  while (iter.hasNext()){
                                         item =;
                                         name = item.getFieldName();
                                         stream = item.openStream();
                    if(item.isFormField()){out.println("Form field " + name + " with value " 
                                               + Streams.asString(stream) + "<br/>");}
                    else {
                          name = item.getName();
                          if(name != null && !"".equals(name)){
                             String fileName = new File(item.getName()).getName();
                             out.println("Client file " + item.getName() + " <br/>with file name "
                                                        + fileName + " uploaded.<br/>");
                             File file = new File(application.getRealPath("/fileUploads/" 
                                                       + fileName));
                             FileOutputStream fos = new FileOutputStream(file);
                             long fileSize = Streams.copy(stream, fos, true);
                                + " was uploaded to the fileUploads folder. Size was " +
                                       fileSize + "<br/>");
  } else out.print("Wrong request type!");

Open in new window

For the Servlet 3.1 API demo I use a Servlet and assume that your web app is configured  to use annotations. You could configure it using web.xml file tags if you want to do that.
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import java.nio.*;
import java.nio.file.*;
public class FileUpload2 extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter(); 
			writer.print("Request content length is " + request.getContentLength() + "<br/>"); 
			for (Part part : request.getParts()){
					writer.println("message is " + request.getParameter("message") + "<br/>");
				} else{
					if(part.getSize() > 100){
						String fileName = new File(part.getSubmittedFileName()).getName();
						Path path = FileSystems.getDefault().getPath(getServletContext().getRealPath("/fileUploads"), fileName);
						long fileSize = Files.copy(part.getInputStream(), path);
						writer.print(fileName + " was uploaded to the fileUploads folder. Size was " + fileSize + "<br/>");
		catch(Exception e){
			writer.print("Error: " + e.toString());

Open in new window

 Use the following to call either of these(with changing the action attribute to point to your JSP)
             <form enctype="multipart/form-data" action="/fileUpload2" method="post">
			       multiple <input type='file' name='file[]' multiple/><br/>
                    <input type='file' name='file1'/><br/>
                    <input type='file' name='file2'/><br/>
                    <input type='file' name='file3'/><br/>
                    Type message:<input type="text" name="message" /><br/>
                    <input Type='submit' value='Submit'/>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Demo code posted.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.