【问题标题】:Error 500: java.lang.StringIndexOutOfBoundsException错误 500:java.lang.StringIndexOutOfBoundsException
【发布时间】:2017-03-10 18:30:01
【问题描述】:

大家好,我一直在寻找解决 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

【问题讨论】:

    标签: java html servlets file-upload input


    【解决方案1】:

    您会看到有关实现 file upload 的 oracle 示例。或者使用commons-fileupload API

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

    【讨论】:

    • 嘿,感谢您的回答,不幸的是它没有工作,因为 getContentLengthLong() 对于 HttpServletRequest 类型未定义任何建议?提前致谢!
    【解决方案2】:

    嗯...我通过写一些完全不同的东西来解决这个问题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 2012-09-01
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多