错误500:java.lang.StringIndexOutOfBoundsException

问题描述:

嗨,大家好我一直在寻找解决在java中的错误500。我已经阅读了同一主题的另一个问题,但我无法修复它。你们能帮我解决我的错误吗?错误500:java.lang.StringIndexOutOfBoundsException

我使用HTML输入文件。将文件上传到C文件夹中:此代码适用于小于1或2kb的文件,但当我上传较大的文件时,我会得到Out Of Bounds Index Error。如果重复,请提前致谢并对不起。

String saveFile = new String(); 
    String contentType = request.getContentType(); 


    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; 

     while(totalBytesRead < formDataLength){ 

     byteRead = in.read(dataBytes , totalBytesRead, formDataLength); 
     totalBytesRead += byteRead; 

     String file = new String(dataBytes); 

     saveFile = file.substring(file.indexOf("filename=\"") + 10); 
     saveFile = saveFile.substring(0, saveFile.indexOf("\n")); 
     saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\"")); 

     int lastIndex = contentType.lastIndexOf("="); 

     String boundary = contentType.substring(lastIndex + 1, contentType.length()); 

     int pos; 

     pos = file.indexOf("filename=\""); 
     pos = file.indexOf("\n", pos) + 1; 
     pos = file.indexOf("\n", pos) + 1; 
     pos = file.indexOf("\n", pos) + 1; 

     int boundaryLocation = file.indexOf(boundary, pos) - 4 ; 

     int startPos = ((file.substring(0, pos)).getBytes()).length; 
     int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; 

     saveFile = "C:/uploadDir2/" + saveFile; 

     File ff = new File(saveFile); 

     try{ 
      FileOutputStream fileOut = new FileOutputStream(ff); 
      fileOut.write(dataBytes, startPos, (endPos - startPos)); 
      fileOut.flush(); 
      fileOut.close(); 
     }//fin try 

     catch(Exception e){ 
//   out.println(e); 
     }//fin catch 



     }//fin while 

}//finif 

嗯......我通过书面方式完全不同的东西解决了这个问题。

import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Iterator; 
import java.util.List; 

import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
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.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 

import dao.FtpFileUpload; 

/** 
* Servlet implementation class ServletCargaEvidencias 
*/ 
@WebServlet("/ServletCargaEvidencias") 
public class ServletCargaEvidencias extends HttpServlet { 
private static final long serialVersionUID = 1L; 

private static final String DATA_DIRECTORY = "data"; 
private static final int MAX_MEMORY_SIZE = 2048 * 2048 * 2; 
private static final int MAX_REQUEST_SIZE = 8192 * 8192; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public ServletCargaEvidencias() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
} 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/ 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
    System.out.println("IniciandoServlet Carga Evidencias"); 

    String ruta = request.getParameter("evidencia"); 



      // Revisamos que se tenga una petición multi part para carga de archivos binarios 
      boolean isMultipart = ServletFileUpload.isMultipartContent(request); 

      if (!isMultipart) { 
       return; 
      } 

      // Creamos una fabrica para archivos basados en disco. 
      DiskFileItemFactory factory = new DiskFileItemFactory(); 

      // Revisamos los limites de tamaño para los cuales los archivos se escribe directo en disco 
      factory.setSizeThreshold(MAX_MEMORY_SIZE); 

      // establece un drectorio donde se almacenarán los archivos 
      // que pesen más allá de los límites permitidos 
      factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 

      // Construcción del folder donde el archivo se va a guardar dentro del root de nuestra web app en WEB-CONTENT 
      String uploadFolder = getServletContext().getRealPath("") 
        + File.separator + DATA_DIRECTORY; 

      // Creamos el manejador de carga de archivos 
      ServletFileUpload upload = new ServletFileUpload(factory); 

      //Establece la constante de máximo tamaño de petición 
      upload.setSizeMax(MAX_REQUEST_SIZE); 

      try { 
       // Parea la petición 
       List items = upload.parseRequest(request); 
       Iterator iter = items.iterator(); 
       while (iter.hasNext()) { 
        FileItem item = (FileItem) iter.next(); 

        if (!item.isFormField()) { 
         String fileName = new File(item.getName()).getName(); 
         String filePath = uploadFolder + File.separator + fileName; 
         File uploadedFile = new File(filePath); 

         //System.out.println("Este es el path del archivo feliz: " + filePath); 

         // Guarda el archivo a la carpeta interna, en el contexto de la aplicación y posteriormente la envía por FTP a un servidor 
         item.write(uploadedFile); 
         FtpFileUpload.cargarArchivos(filePath, fileName); 
        } 
       } 

       // Nos muetra otro servlet o jsp posteriormente a la carga 
       getServletContext().getRequestDispatcher("/Secure/evidencias.jsp").forward(
         request, response); 

      } catch (FileUploadException ex) { 
       throw new ServletException(ex); 
      } catch (Exception ex) { 
       throw new ServletException(ex); 
      } 







}// fin del post----- 

}// fin de la clase----- 

你看到oracle实例file upload的例子。或者使用commons-fileupload的API

您需要使用getContentLengthLong非常大的文件大小,因为getContentLength()方法定义为int

+0

嘿感谢您的回答不幸,它没有工作,因为getContentLengthLong()是未定义的类型HttpServletRequest任何建议?提前致谢! –