多部分实体文件上传 java.lang.ArrayIndexOutOfBoundsException
Multipart entity file uploading java.lang.ArrayIndexOutOfBoundsException
使用文件数组上传多部分实体文件。
我在下面提到了错误代码,请帮我解决这个问题。异常java.lang.ArrayIndexOutOfBoundsException:长度=2;指数=2。
提前致谢。
代码:
try{
int i = 0;
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = new DefaultHttpClient();
int selectedImgLength = selectedItems.size();
File[] mfile = new File[selectedImgLength];
for( i = 0; i<selectedImgLength;i++){
//mfile[i]= selectedItems.get(i);// Error InCompatiable type
mfile[i] = new File(selectedItems.get(i));
}
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addPart( "userfile[" + i + "]", new FileBody(mfile[i]));
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
System.out.println("POST IMAGE Response"+response);
}catch(Exception e){e.printStackTrace();}
当你这样做时
entityBuilder.addPart( "userfile[" + i + "]", new FileBody(mfile[i]));
您已经退出 for 循环并且 i
的大小等于 selectedImgLength
,因此您将得到 ArrayIndexOutOfBoundsException
尝试更改以便将文件添加到 for 循环内的 entityBuilder
。
使用文件数组上传多部分实体文件。 我在下面提到了错误代码,请帮我解决这个问题。异常java.lang.ArrayIndexOutOfBoundsException:长度=2;指数=2。 提前致谢。
代码:
try{
int i = 0;
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = new DefaultHttpClient();
int selectedImgLength = selectedItems.size();
File[] mfile = new File[selectedImgLength];
for( i = 0; i<selectedImgLength;i++){
//mfile[i]= selectedItems.get(i);// Error InCompatiable type
mfile[i] = new File(selectedItems.get(i));
}
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addPart( "userfile[" + i + "]", new FileBody(mfile[i]));
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
System.out.println("POST IMAGE Response"+response);
}catch(Exception e){e.printStackTrace();}
当你这样做时
entityBuilder.addPart( "userfile[" + i + "]", new FileBody(mfile[i]));
您已经退出 for 循环并且 i
的大小等于 selectedImgLength
,因此您将得到 ArrayIndexOutOfBoundsException
尝试更改以便将文件添加到 for 循环内的 entityBuilder
。