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 : 8.0.9.0

Can anybody please help me to resolve this issue?

Html file

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <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">
 </FORM>


</body>
</html>
JSP Code

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

<%@ page import="org.apache.commons.io.FileUtils" %>

<%@ page import="java.io.*"%>
<%@ 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>";
    try
    {
        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");
                    counter++;
                }                 else
                {
                    resp = "<br>The user did not upload a file for this part.";
                }
            }
        }// end while
                }
    catch (java.io.IOException ioe)
    {
        out.println(ioe);
        resp = ioe.getMessage();
    }    
%>
byox deveAsked:
Who is Participating?
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.

rrzCommented:
Are you and
http://www.experts-exchange.com/members/varunbansal.html 
the same person?  
If not, then why is your code the same as posted at
http://www.experts-exchange.com/questions/28737725/Multiple-Images-Upload-JSP-Web-application.html   
If yes, then why didn't you respond to my comment in your first question?
0
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..
0
rrzCommented:
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.*,
                 java.io.*,
                 org.apache.commons.fileupload.*,
                 org.apache.commons.fileupload.servlet.*,
                 org.apache.commons.fileupload.disk.*,
                 org.apache.commons.fileupload.util.*"%>
<%
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  out.print("Request content length is " + request.getContentLength() + "<br/>"); 
  if(isMultipart){
                  ServletFileUpload upload = new ServletFileUpload();
                  FileItemIterator iter = upload.getItemIterator(request);
                  FileItemStream item = null;
                  String name = "";
                  InputStream stream = null;
                  while (iter.hasNext()){
                                         item = iter.next();
                                         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);
                             out.print(fileName 
                                + " 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 java.io.*;
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.*;
@WebServlet("/fileUpload2")
@MultipartConfig
public class FileUpload2 extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter(); 
		try{
			writer.print("Request content length is " + request.getContentLength() + "<br/>"); 
			for (Part part : request.getParts()){
				if(part.getName().equals("message")){
					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)
<html><body>
             <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'/>
             </form>
 </body></html>

Open in new window

0

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
rrzCommented:
Demo code posted.
0
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
JSP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.