0

I have a JSP page and a servlet.The JSP has two input, one being the File and the other is a text input.When user clicks on the SUBMIT button the Form action points to Servlet`s do Post().In Do Post() I have didvided the code into two part.The one part retrives the text input and File name from Jsp page and the other converts the file into bytes.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                    IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

    //This is 1st part
    //For Converting the File into Stream of Bytes
    String contentType = request.getContentType();
    //System.out.println("Content type is :: " +contentType);

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        int k = -1;
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);

            totalBytesRead += byteRead;
            //System.out.println(dataBytes[++k]);

        }
        for (int i = 0; i < formDataLength; i++) {
            System.out.print((char)dataBytes[i]);

        }

        System.out.println("Converted");
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>UPLOADED FILE</H1>");
        out.println("<BODY>");
        out.println("</HTML>");
    } else
        System.out.println("asa");


    //This is the 2nd part
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    // parse request
    List items = null;

    // get uploaded file
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
    }
    FileItem file = (FileItem)items.GET(1);
    String DocTitle = file.getName();

    int len = DocTitle.length(), pos = 0, j = 2;
    for (int i = 0; i < len; i++) {

        if (DocTitle.charAt(i) == 46) {
            pos = i;

        }

    }

    String s = DocTitle.substring(pos + 1, len);
    System.out.println("TheContent Type is: " + s);

    // get taget filename
    FileItem name = (FileItem)items.get(1);
    String fileName = name.getString();
    System.out.println("Filename: " + fileName + "." + s);

}

The problem is if i only run only the 1st part or 2nd part the code works but together they dont seem to work.If both are put together then the 1st part get executed and for 2nd part it throws

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.RangeCheck(ArrayList.java:547)

Please help me to solve the above

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
Sankalp
  • 173
  • 2
  • 9
  • 25
  • In the exception there seems to be some ArrayList object, but i see non in your code. Where is that ArrayList? – MaVRoSCy Sep 19 '12 at 08:50
  • Have you tried this answer ? Possible duplicate: http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet?rq=1 – Hardik Mishra Sep 19 '12 at 08:51
  • As far as my understanding this is beacuse when the 1st part is executed it reaches the end of the file therefore when it tries to read the file it throws ArrayIndexOutOfBoundException.Also if I Put the 2nd part 1st and then execute then the 1st part does not execute as byteRead increases negatively and it is caused in endless help.Please help me with some code in which i can retrive the form field from jsp as well as convert the file into bytes – Sankalp Sep 19 '12 at 11:20

1 Answers1

1

Your concrete mistake is that you're attempting to read the HTTP request body twice. The first time using request.getInputStream() with apparently the sole purpose to print it to the stdout (perhaps a careless debug attempt?). The second time using Apache Commons FileUpload. However, it would retrieve a completely empty request body by request.getInputStream(), because you've already consumed it beforehand! The client ain't going to re-send the file for a second time so that you can read it for a second time (using Apache Commons FileUpload).

Remove that 1st block altogether and it should work.

Oh, please stop reading roseindia.net. That site only shows misleading code examples and teaches extremely bad practices which confuses starters altogether.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Use `FileItem#get()` to get the uploaded file as an in-memory `byte[]`. You can then read it as many times as you want. I only do by far not understand how exactly the 1st part of your code is ever useful. It seems to only corrupt the file content. Why don't you just save the retrieved file just straight to the disk? – BalusC Oct 03 '12 at 11:30
  • I cannot.I am consuming webservice where i have to pass the input text field content and files as bytes...I dont have to save it on disk.ALso kindly refer to my new post where i have made little improvemnt but again struck.Kindly help me with this http://stackoverflow.com/questions/12708046/unable-to-retreive-form-element-in-servlet-from-jsp-when-enctype-multipart-form – Sankalp Oct 03 '12 at 12:02
  • Then just use `FileItem#get()`, provided that you've properly **removed** any calls to `request.getInputStream()`, `getParameter()`, etc as they would only consume the request body, as explained in the above answer. – BalusC Oct 03 '12 at 12:04
  • Kindly visit this link.I am almost close to solve this issue but struck http://stackoverflow.com/questions/12708046/unable-to-retreive-form-element-in-servlet-from-jsp-when-enctype-multipart-form – Sankalp Oct 03 '12 at 12:06