文件上传并使用JSP和servlet转换为字节

时间:2012-09-19 08:42:17

标签: jsp servlets file-upload byte indexoutofboundsexception

我有一个JSP页面和一个servlet.SJK有两个输入,一个是File,另一个是文本输入。当用户点击SUBMIT按钮时,Form操作指向Servlet的do Post()。在Do Post()中,我将代码分为两部分。一部分从Jsp页面中检索文本输入和文件名,另一部分将文件转换为字节。

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);

}

问题是如果我只运行第一部分或第二部分代码工作但是它们似乎一起工作。如果两者都放在一起然后第一部分被执行而第二部分它会抛出

  

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

请帮我解决上面的问题

0 个答案:

没有答案