我有一个 JSP 页面和一个 servlet。JSP 有两个输入,一个是文件,另一个是文本输入。当用户单击提交按钮时,表单操作指向 Servlet 的 do Post()。在 Do Post () 我将代码分为两部分。一部分从 Jsp 页面中检索文本输入和文件名,另一部分将文件转换为字节。
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
//This is 1st part
//For Converting the File into Stream of Bytes
String contentType = request.getContentType();
//System.out.println("Content type is :: " +contentType);
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;
int k = -1;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
//System.out.println(dataBytes[++k]);
}
for (int i = 0; i < formDataLength; i++) {
System.out.print((char)dataBytes[i]);
}
System.out.println("Converted");
out.println("<HTML>");
out.println("<HEAD>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H1>UPLOADED FILE</H1>");
out.println("<BODY>");
out.println("</HTML>");
} else
System.out.println("asa");
//This is the 2nd part
// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
// parse request
List items = null;
// get uploaded file
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
}
FileItem file = (FileItem)items.GET(1);
String DocTitle = file.getName();
int len = DocTitle.length(), pos = 0, j = 2;
for (int i = 0; i < len; i++) {
if (DocTitle.charAt(i) == 46) {
pos = i;
}
}
String s = DocTitle.substring(pos + 1, len);
System.out.println("TheContent Type is: " + s);
// get taget filename
FileItem name = (FileItem)items.get(1);
String fileName = name.getString();
System.out.println("Filename: " + fileName + "." + s);
}
问题是,如果我只运行第一部分或第二部分,代码可以工作,但它们似乎不起作用。如果两者放在一起,那么第一部分会被执行,第二部分会抛出
java.lang.IndexOutOfBoundsException:索引:0,大小:0 在 java.util.ArrayList.RangeCheck(ArrayList.java:547)
请帮我解决以上问题