将pic上传到服务器时出现java.lang.IndexOutOfBoundsException

时间:2012-04-21 15:34:09

标签: java file jsp servlets file-upload

我尝试将文件上传到服务器时收到java.lang.IndexOutOfBoundsException。

我检查了loaclhost的代码,它工作正常, 但在将其上传到服务器后我收到了错误。

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();
     }
    }
  }
}

错误讯息:

   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.

2 个答案:

答案 0 :(得分:0)

您正在以下语句中保存文件:

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();

然后在加载到数据库时尝试读取不同的文件:

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看起来像是浏览器上传的文件的名称,而不是保存上传内容的文件

更改以下内容:

// fis = new FileInputStream(f);
fis = new FileInputStream(
    new File("/opt/tomcat/webapps/ROOT/images/user/profile/"+ff));

答案 1 :(得分:0)

更改以下行并尝试..

String file = new String(dataBytes); String file = new String(dataBytes,“CP1256”);

int startPos =((file.substring(0,pos))。getBytes())。length; int startPos =((file.substring(0,pos))。getBytes(“CP1256”))。length;

int endPos =((file.substring(0,boundaryLocation))。getBytes())。length; int endPos =((file.substring(0,boundaryLocation))。getBytes(“CP1256”))。length;