在服务器端上传图像阵列

时间:2015-07-04 10:18:45

标签: android

我正在尝试添加用户从图库中选择的任意数量的图片,并在服务器端添加一次。但只添加了一个图像。我的图像数组上传条件是temp == 1.

这是我的代码:

private String uploadFile() {
            String responseString = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new ProgressListener() {

                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });
                if(temp==1)
                {
                for (int i = 0; i < filePatharr.length; i++) {
                    File sourceFile = new File(filePatharr[i]);
                    entity.addPart("image", new FileBody(sourceFile));
                }
                }
                if(temp==0)
                {
                File sourceFile = new File(filePath);

                // Adding file data to http body
                entity.addPart("image", new FileBody(sourceFile));
                }
                /*
                 * // Extra parameters if you want to pass to server
                 * entity.addPart("website", new
                 * StringBody("www.androidhive.info")); entity.addPart("email",
                 * new StringBody("abc@gmail.com"));
                 */

                totalSize = entity.getContentLength();
                httppost.setEntity(entity);

                // Making server call
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // Server response
                    responseString = EntityUtils.toString(r_entity);
                } else {
                    responseString = "Error occurred! Http Status Code: "
                            + statusCode;
                }

            } catch (ClientProtocolException e) {
                responseString = e.toString();
            } catch (IOException e) {
                responseString = e.toString();
            }

            return responseString;

        }

filePatharr是我的字符串数组,我在其中获取图像路径。在我的结尾或后端(PHP方面)是否存在问题。任何人都可以帮助我PLZ

1 个答案:

答案 0 :(得分:0)

for (int i = 0; i < filePatharr.length; i++) {
    File sourceFile = new File(filePatharr[i]);
    entity.addPart("image", new FileBody(sourceFile));
}

你总是会覆盖HTTP POST image 参数,因此只会上传最后一张图片(或者第一张,我不知道apache的库是如何工作的。)

例如,您可以使用“image”+ i 作为帖子参数,此外,您可以传递“numOfImages”帖子参数以了解上传的图片数量。