0

Am getting java.lang.IndexOutOfBoundsException while I try to uplaod a file to server.

I checked the code at loaclhost and it was working fine, but after uploading it to the server am getting the error.

upload.jsp

    <form action="UploadServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="select"  value="" />
    <input type="submit" value="Select Profile Pic" />
    </form>

UploadServlet.java

  /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 package file_upload;
 import java.io.IOException;
 import java.io.PrintWriter;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.sql.*;
 /**
 *
 * @author Dan
 */
 public class UploadServlet extends HttpServlet {
 public void doPost(HttpServletRequest request,HttpServletResponse response) throws        ServletException,IOException {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
  HttpSession session = request.getSession(true);
  String d1 = session.getAttribute("user_id").toString();
     String saveFile="";
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;
File ff = new File(d1+".gif"); //IMP NOTE: TO RENAME THE FILE TO userig.gif
FileOutputStream fileOut = new FileOutputStream("/opt/tomcat/webapps/ROOT/images/user/profile/"+ff); //IMP NOTE : THE DIR TO STORE FILE AT
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
out.println("You have successfully upload the file:"+saveFile);
Connection connection = null;
String connectionURL = "jdbc:mysql://mysql-ypmdb.jelastic.servint.net/bmdb";
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "4x0dD9d8rZ");
File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){
    e.printStackTrace();
     }
    }
  }
}

Error message:

   type Exception report
  message
  description The server encountered an internal error () that prevented it from     fulfilling this request.
  exception
java.lang.IndexOutOfBoundsException
java.io.FileOutputStream.writeBytes(Native Method)
java.io.FileOutputStream.write(FileOutputStream.java:318)
file_upload.UploadServlet.doPost(UploadServlet.java:62)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.14 logs.
Lion
  • 18,729
  • 22
  • 80
  • 110
Batman
  • 29
  • 4
  • 1
    Add a System.out.println() statement before the fileOut.write to log the values of startPos and endPos, as one of them is causing the write to be outside the bounds of the dataBytes array. May i also suggest you check out http://commons.apache.org/fileupload/ - commons upload which abstracts you from all this logic – Chris White Apr 21 '12 at 16:06
  • @Chris As suggested I added System.out.println() statement (at localhost) then I got these different start and endPos- `startPos = 147 endPos = 879541 java.io.FileNotFoundException: abstract.jpg (The system cannot find the file specified)` `startPos = 142 endPos = 777977 java.io.FileNotFoundException: Penguins.jpg (The system cannot find the file specified)` `startPos = 144 endPos = 561420 java.io.FileNotFoundException: Lighthouse.jpg` `startPos = 140 endPos = 846081 java.io.FileNotFoundException: Desert.jpg` All files were uploaded successfully on my local hard disk – Batman Apr 21 '12 at 17:05
  • So now you're getting FilenotFoundExceptions - which line is this thrown in the code block above? I'm assuming `fis = new FileInputStream(f);` – Chris White Apr 21 '12 at 17:10
  • @ChrisWhite yes But my files are being uploaded to my mentioned folder at my local hard disk But when I try to upload at my web host server I am getting java.lang.IndexOutOfBoundsException – Batman Apr 21 '12 at 17:13
  • Oh boy, one more victim of roseindia.net... http://stackoverflow.com/questions/5038798/uploading-of-pdf-file/5041420#5041420 – BalusC Apr 21 '12 at 20:53
  • Please don't show us your unmodified IDE hints how to handle templates. – user unknown Apr 22 '12 at 14:07

2 Answers2

0

You are saving the file in the following statements:

File ff = new File(d1+".gif"); //IMP NOTE: TO RENAME THE FILE TO userig.gif
FileOutputStream fileOut = 
    new FileOutputStream("/opt/tomcat/webapps/ROOT/images/user/profile/"+ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

And then trying to read in a different file when loading into the Database:

File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));

saveFile looks like the name of the file uploaded by the browser, not the file where the uploaded content was saved

Change the following:

// fis = new FileInputStream(f);
fis = new FileInputStream(
    new File("/opt/tomcat/webapps/ROOT/images/user/profile/"+ff));
Chris White
  • 29,949
  • 4
  • 71
  • 93
  • Sorry, my problem still persists. Allow me to re-state my problem 'java.lang.IndexOutOfBoundsException **while uploading pic to server**' The changes you suggested removed the `FilenotFoundExceptions` at **localhost** only. Although files are being uploaded while I run the code at localhost with file path ('F://my_floder/'), but when I run the same code with diff file path ("/opt/tomcat/webapps/ROOT/images/user/profile/"+ff), I am getting the above stated error. – Batman Apr 21 '12 at 18:08
  • ok, on the server, add another debug println to output the length of dataBytes and add the debug output back into your original question (rather than a comment - makes it much easier to review) – Chris White Apr 21 '12 at 18:36
0

change the following lines and try ..

String file = new String(dataBytes); to String file = new String(dataBytes,"CP1256");

int startPos = ((file.substring(0, pos)).getBytes()).length; to int startPos = ((file.substring(0, pos)).getBytes("CP1256")).length;

int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; to int endPos = ((file.substring(0, boundaryLocation)).getBytes("CP1256")).length;