2016-10-27 4 views
-1

こんにちは、私は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 

答えて

0

intとして定義されているので、非常に大きなファイルサイズのためgetContentLengthLongを使用する必要がcommons-fileuploadのAPI

を使用しています。

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----- 
0

あなたはfile uploadを実装する上でのOracleの例を参照してください。それともあなたはgetContentLength()方法がうーん...私は完全に別の何かを足すことによって、これを固定

+0

getContentLengthLong()が型HttpServletRequestの任意の提案に対して定義されていないため、ちょっとあなたの答えを不幸にしてくれました。前もって感謝します! –