2016-10-12 67 views
-2

多部分實體文件上傳文件數組。 我已經提到了下面的錯誤代碼,請幫我解決這個問題。異常java.lang.ArrayIndexOutOfBoundsException:length = 2;索引= 2。 在此先感謝。多部分實體文件上傳java.lang.ArrayIndexOutOfBoundsException

代碼:

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

我可以知道爲什麼我的問題得到了投票。請給我評論,這將有助於改善問題的堆棧。 –

回答

1

當你做

entityBuilder.addPart("userfile[" + i + "]", new FileBody(mfile[i])); 

您已經退出for循環和i已成爲等於在尺寸上selectedImgLength,因此,你會得到一個ArrayIndexOutOfBoundsException

嘗試更改以便將文件添加到for循環中的entityBuilder

+0

感謝兄弟,對不起,我犯了一個大錯誤。感謝您的指導。現在我修正了它。 –