![](/img/trans.png)
[英]Cannot upload the Image to server java.lang.IndexOutOfBoundsException:
[英]java.lang.IndexOutOfBoundsException when try to upload file on server
我以前的帖子已刪除,因此我在這里重新發布,因為我沒有任何消除此錯誤的線索。
錯誤:
java.lang.IndexOutOfBoundsException
java.io.FileOutputStream.writeBytes(Native Method)
java.io.FileOutputStream.write(FileOutputStream.java:297)
com.ninenexus.simplesign.storeanddisplay.StoreAndDisplayImage.doPost(StoreAndDisplayImage.java:85)
javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
代碼:
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 = "d:/" + saveFile;
try
{
File f = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(f);
fileOut.write(dataBytes, startPos, (endPos - startPos)); // Line 85
fileOut.flush();
fileOut.close();
}
catch(...)
{
...
}
}
else
{
...
}
行號的輸出 85是
dataBytes=[B@676e3f, startPos=142, (endPos - startPos)=75944.
我試圖通過輸入type ='file'從用戶那里獲取文件,然后使用此代碼將其保存在目錄中。 它在tomcat服務器上正常工作。 文件被保存在目錄中。 但是,當我創建war文件並將其上傳到服務器上時。 嘗試在主服務器上運行此代碼時,出現此錯誤。 沒有解決這個問題的線索。 幫助真的很感激。
該錯誤很可能是由您確定開始位置和結束位置的“有趣”方式引起的。 您使用字節到字符串的轉換,然后使用計算機的當前默認編碼返回。 開發和生產環境之間的默認編碼很可能會有所不同。 這解釋了環境之間的差異。
對於許多編碼,有些字節序列無法解碼為字符。 然后,字符串將包含一些替換字符。 當您將字符串轉換回字節序列時,長度可能會與之前不同,並且位置錯誤。
更改以下行,然后嘗試..
字符串文件=新字符串(dataBytes); 到 String文件=新的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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.