上传文件时出现 IndexOutOfBoundsException - Java
我在上传 zip 文件时遇到 IndexOutOfBoundsException。可能是什么原因?我该如何解决?
代码:-
String sf="";
String contentType = req.getContentType();
DataInputStream in = new DataInputStream(req.getInputStream());
int formDataLength = req.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);
String 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;
sf = "../" + File.separator + saveFile;
FileOutputStream fileOut = new FileOutputStream(sf);
fileOut.write(dataBytes, startPos, (endPos - startPos)); //----- Exception occurs on this line.
fileOut.flush();
fileOut.close();
Stacktrace:-
java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:297)
at com.apprika.servlets.UpgradePatchServlet.uploadFile(UpgradePatchServlet.java:77)
at com.apprika.servlets.UpgradePatchServlet.upgradeServer(UpgradePatchServlet.java:40)
at com.apprika.servlets.UpgradePatchServlet.doPost(UpgradePatchServlet.java:30)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Thread.java:636)
服务器在 Linux 上运行并从 Windows 上传文件。
我已经尝试过 apache commons 文件上传但仍然没有成功。
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream is = item.getInputStream();
FileOutputStream os = new FileOutputStream("/up/" + item.getName());
byte[] b = new byte[4096];
int bytesRead = 0;
while ((bytesRead = is.read(b)) != -1) {
os.write(b, 0, bytesRead);
}
os.flush();
os.close();
is.close();
}
}
}catch (Exception e) {
e.printStackTrace();
}
现在它给出错误 java.io.FileNotFoundException: /up (Is a directory)
`
I'm getting IndexOutOfBoundsException while uploading a zip file. What could be the reason? How can I solve it?
Code:-
String sf="";
String contentType = req.getContentType();
DataInputStream in = new DataInputStream(req.getInputStream());
int formDataLength = req.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);
String 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;
sf = "../" + File.separator + saveFile;
FileOutputStream fileOut = new FileOutputStream(sf);
fileOut.write(dataBytes, startPos, (endPos - startPos)); //----- Exception occurs on this line.
fileOut.flush();
fileOut.close();
Stacktrace:-
java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:297)
at com.apprika.servlets.UpgradePatchServlet.uploadFile(UpgradePatchServlet.java:77)
at com.apprika.servlets.UpgradePatchServlet.upgradeServer(UpgradePatchServlet.java:40)
at com.apprika.servlets.UpgradePatchServlet.doPost(UpgradePatchServlet.java:30)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Thread.java:636)
Server is running on Linux and uploading file from Windows.
I've tried apache commons file upload but still not getting any success.
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream is = item.getInputStream();
FileOutputStream os = new FileOutputStream("/up/" + item.getName());
byte[] b = new byte[4096];
int bytesRead = 0;
while ((bytesRead = is.read(b)) != -1) {
os.write(b, 0, bytesRead);
}
os.flush();
os.close();
is.close();
}
}
}catch (Exception e) {
e.printStackTrace();
}
Now it gives error java.io.FileNotFoundException: /up (Is a directory)
`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在将上传的字节转换为字符串,而不指定编码。服务器上的默认编码不必与上传时使用的编码相同。
因此,不能保证字符串长度与字节数组长度相同,因此根据字符串计算该数组的偏移量可能会导致各种问题。
我建议使用类似 Apache Commons Fileupload 的东西,而不是尝试自己完成所有解析以获取所有内容细节正确并不容易。
一个很好的起点是这个答案:如何将文件上传到使用 JSP/Servlet 的服务器?
You are converting the uploaded bytes into a string without specifying the encoding. The default encoding on the server is not necessary the same as the one used for the upload.
Therefore the strings length is not guaranteed to be the same as the byte arrays length, so computing the offsets into this array based on the string could lead to all sorts of problems.
I would recommend using something like Apache Commons Fileupload instead of trying to do all the parsing yourself as getting all the details right is not easy.
A good starting point would be this answer: How to upload files to server using JSP/Servlet?
问题在于如何提取 startPos 和 endPos 值,从而导致无效的偏移量。我建议您在调试器中仔细检查提取的值,您会发现解析表单数据的代码有问题。
The problem is in how you extract the startPos and endPos values, resulting in invalid offsets. I suggest you carefully examine the values being extracted, in a debugger, and you'll find that something's wrong with the code that parses the form data.
更改以下行并尝试 ..
to
和
to
和
to
change the following lines and try ..
to
and
to
and
to