簡體   English   中英

我想使用jsp servlet從apachecommons文件上傳中上傳圖像,但是它將顯示java.lang.StringIndexOutOfBoundsException

[英]I want to upload image from apachecommons file upload using jsp servlet but it will show java.lang.StringIndexOutOfBoundsException

這是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]

我希望它將為每個用戶創建運行時文件夾和子文件夾.....

您的問題在這條線上:

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

這是Upload.java源文件的第72行,您可以從堆棧跟蹤中輕松獲取。

ofileName不包含任何\\字符,因此lastIndexOf返回-1 ,該substring不能用作起始索引。 嘗試執行此操作將為您提供正得到的異常。

相反,請執行此操作。

int nameStart = ofileName.lastIndexOf("\\");
if (nameStart > -1) {
    finalName = ofileName.substring(nameStart);
} else {
    finalName = ofileName;  // there's nothing to substring
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM