Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误500:java.lang.StringIndexOutOfBoundsException_Java_Html_Servlets_File Upload_Input - Fatal编程技术网

错误500:java.lang.StringIndexOutOfBoundsException

错误500:java.lang.StringIndexOutOfBoundsException,java,html,servlets,file-upload,input,Java,Html,Servlets,File Upload,Input,大家好,我一直在寻找解决java中错误500的方法。我读过另一个与同一主题有关的问题,但我无法解决它。你们能帮我解决我的错误吗 我使用HTML输入文件。将文件上载到C文件夹:此代码适用于小于1或2kb的文件,但当我上载较大的文件时,会出现越界索引错误。提前感谢,如有重复,恕不另行通知 String saveFile = new String(); String contentType = request.getContentType(); if((contentType !=

大家好,我一直在寻找解决java中错误500的方法。我读过另一个与同一主题有关的问题,但我无法解决它。你们能帮我解决我的错误吗

我使用HTML输入文件。将文件上载到C文件夹:此代码适用于小于1或2kb的文件,但当我上载较大的文件时,会出现越界索引错误。提前感谢,如有重复,恕不另行通知

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
String saveFile=new String();
String contentType=request.getContentType();
if((contentType!=null)&&(contentType.indexOf(“多部分/表单数据”)>=0)){
DataInputStream in=新的DataInputStream(request.getInputStream());
int formDataLength=request.getContentLength();
字节数据字节[]=新字节[formDataLength];
int byteRead=0;
int totalBytesRead=0;
while(totalBytesRead
您可以看到oracle关于实现或使用API的示例


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

嗯……我通过编写完全不同的内容来解决这个问题

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

嘿,谢谢你的回答,不幸的是,它不起作用,因为HttpServletRequest类型的getContentLengthLong()未定义任何建议??提前谢谢!