Multipart entity file uploading java.lang.ArrayIndexOutOfBoundsException

我是研究僧i 提交于 2019-12-13 10:53:25

问题


Multipart entity file uploading with array of files. I have mentioned the error code below, please help me resolve this issue. Exception java.lang.ArrayIndexOutOfBoundsException: length=2; index=2. Thanks in Advance.

Code:

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

回答1:


when you do

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

you have already exited the for loop and i has become equals in size to selectedImgLength, therefore you will get a ArrayIndexOutOfBoundsException

try changing so that adding the file to the entityBuilder within the for loop.



来源:https://stackoverflow.com/questions/39991118/multipart-entity-file-uploading-java-lang-arrayindexoutofboundsexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!