我想使用jsp servlet从apachecommons文件上传上传图像,但它会显示java.lang.StringIndexOutOfBoundsException

时间:2013-11-13 10:05:58

标签: java jsp servlets

这是eclipse显示的错误 ![这个eclipse文件夹结构] [1]

Nov 13, 2013 6:46:38 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Image] in context with path [/uploadimg] threw exception
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at com.vaibhav.upload.doPost(upload.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

............................................... ...........................................

UPLOAD.java(servlet代码)

package com.vaibhav;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
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;
import org.imgscalr.Scalr;

public class upload extends HttpServlet {
    private boolean isMultipart;
    String ofileName;
    String fieldName;
    String contentType;
    File usersDir = null;

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("hhhhhhhhhhhhhhhhhhhhhhhh");
        if (!isMultipart) {
        } else {

            File fobj = new File(getServletContext().getRealPath("\\"));
            FileItemFactory factory = new DiskFileItemFactory(1024 * 5, fobj);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            System.out.println("hiiiiiiiiiiiiiiiiiiiiiiiii");
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            System.out.println(items);
            Iterator itr1 = items.iterator();
            FileItem fileItem = null;

            while (itr1.hasNext()) {
                FileItem item = (FileItem) itr1.next();
                if (item.isFormField()) {
                    item.getFieldName();
                    item.getString();
                } else {
                    fileItem = item;
                    String finalName;
                    fieldName = item.getFieldName();
                    ofileName = item.getName();
                    contentType = fileItem.getContentType();
                    finalName = ofileName
                            .substring(ofileName.lastIndexOf("\\"));
                    finalName = ofileName;
                    usersDir = new File(getServletContext().getRealPath("\\")
                            + "\\users\\" + "\\images\\" + finalName);
                    try {
                        fileItem.write(usersDir);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String imgExt = usersDir.getAbsolutePath().substring(
                            usersDir.getAbsolutePath().lastIndexOf(".") + 1);
                    BufferedImage bimg = new BufferedImage(100, 100,
                            BufferedImage.TYPE_INT_RGB);
                    bimg.createGraphics().drawImage(
                            ImageIO.read(usersDir).getScaledInstance(170, 150,
                                    java.awt.Image.SCALE_SMOOTH), 0, 0, null);
                    BufferedImage bimg2 = Scalr.resize(bimg, 150);
                    ImageIO.write(bimg2, imgExt, new File(getServletContext()
                            .getRealPath("\\")
                            + "\\users\\"
                            + "\\images\\thumb_" + finalName));
                }
                RequestDispatcher dispatcher = getServletContext()
                        .getRequestDispatcher("/WEB-INF/webpages/home.jsp");
                dispatcher.forward(request, response);
            }
        }
    }
}

............................................... ............................................ index.jsp的

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>file upload</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" size="50"><br/> <input
            type="submit" value="uploadfile">
    </form>
</body>
</html>

![控制台上显示的错误] [10]

我希望它会为每个用户创建运行时文件夹和子文件夹.....

1 个答案:

答案 0 :(得分:2)

你的问题就在这一行:

finalName = ofileName.substring(ofileName.lastIndexOf("\\"));

这是在Upload.java的源文件的第72行,您可以从堆栈跟踪中轻松获取。

ofileName不包含任何\个字符,因此lastIndexOf返回-1 substringint nameStart = ofileName.lastIndexOf("\\"); if (nameStart > -1) { finalName = ofileName.substring(nameStart); } else { finalName = ofileName; // there's nothing to substring } 不能用作开始索引。试图这样做会给你一个正常的例外。

相反,这样做。

{{1}}
相关问题