“改造”在一个多部分请求中附加的多个图像

时间:2014-08-11 17:29:04

标签: android multipart retrofit

有没有办法在一个多部分请求中附加多个图像?根据用户选择的图像数量,图像是动态的。

以下代码仅适用于单张图片:

接口:

@Multipart
@POST("/post")
void createPostWithAttachments( @Part("f[]") TypedFile image,@PartMap Map<String, String> params,Callback<String> response);

实现:

TypedFile file = new TypedFile("image/jpg", new File(gallery.sdcardPath));

Map<String,String> params = new HashMap<String,String>();
params.put("key","value");

ServicesAdapter.getAuthorizeService().createPostWithAttachments(file,params, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            DBLogin.updateCookie(response);
            new_post_text.setText("");
            try {
                JSONObject json_response = new JSONObject(s);
                Toast.makeText(getApplicationContext(), json_response.getString("message"), Toast.LENGTH_LONG).show();
                if (json_response.getString("status").equals("success")) {
                    JSONObject dataObj = json_response.getJSONObject("data");
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Log.d(TAG, "Request failed");
                }
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Toast.makeText(getApplicationContext(), retrofitError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

2 个答案:

答案 0 :(得分:30)

查看改造后提供的文档。 我能够通过我自己的解决方案完成它,可能不是那么好但仍然设法让它工作..

以下是参考资料 MultipartTypedOutput

实际上与上面的代码非常相似,只是做了一点改动

<强>接口

@POST("/post")
void createPostWithAttachments( @Body MultipartTypedOutput attachments,Callback<String> response);

<强>实施

    MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    multipartTypedOutput.addPart("c", new TypedString(text));
    multipartTypedOutput.addPart("_t", new TypedString("user"));
    multipartTypedOutput.addPart("_r", new TypedString(userData.user.id));

    //loop through object to get the path of the images that has picked by user
    for(int i=0;i<attachments.size();i++){
        CustomGallery gallery = attachments.get(i);
        multipartTypedOutput.addPart("f[]",new TypedFile("image/jpg",new File(gallery.sdcardPath)));
    }

    ServicesAdapter.getAuthorizeService().createPostWithAttachments(multipartTypedOutput, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            DBLogin.updateCookie(response);
            new_post_text.setText("");
            try {
                JSONObject json_response = new JSONObject(s);
                Toast.makeText(getApplicationContext(), json_response.getString("message"), Toast.LENGTH_LONG).show();
                if (json_response.getString("status").equals("success")) {
                    JSONObject dataObj = json_response.getJSONObject("data");
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Log.d(TAG, "Request failed");
                }
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Toast.makeText(getApplicationContext(), retrofitError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

也许这种解决方案并不是那么好,但希望它可以帮助别人。

如果有更好的解决方案请建议,谢谢:D

更新

Retrofit 2.0.0-beta1中不再存在

MultipartTypedOutput

对于想要上传多张图片的用户,现在可以使用 @PartMap ,参考链接javadoc

答案 1 :(得分:4)

//We need to create the Typed file array as follow and add the images path in the arrays list.



    private ArrayList<TypedFile> images;

        private void postService(final Context context) {
            Utils.progressDialog(context);
            MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
            multipartTypedOutput.addPart("user_id",new TypedString(strUserId));
            multipartTypedOutput.addPart("title", new TypedString(strJobtitle));
            multipartTypedOutput.addPart("description", new TypedString(
                    strJobdescription));
            multipartTypedOutput.addPart("experience", new TypedString(
                    strUserExperience));
            multipartTypedOutput.addPart("category_id", new TypedString(
                    strPostCategory));
            multipartTypedOutput.addPart("city_id", new TypedString(strCityCode));
            multipartTypedOutput.addPart("country_id", new TypedString(
                    strCountryCode));       
    multipartTypedOutput.addPart("profile_doc",new TypedFile("multipart/form-data", postCurriculamFile));
    for (int i = 0; i < images.size(); i++) {
                multipartTypedOutput.addPart("image[]", images.get(i));
    }       

    PostServiceClient.getInstance().postServiceData(multipartTypedOutput,
                    new Callback<RegistrationResponsModel>() {
                @Override
                public void failure(RetrofitError retrofitError) {
                    Logger.logMessage("fail" + retrofitError);
                    Utils.progressDialogdismiss(context);
                }

                @Override
                public void success(
                        RegistrationResponsModel regProfileResponse,
                        Response arg1) {
                    Utils.progressDialogdismiss(context);
                    UserResponse(regProfileResponse);
                }
            });
        }


    @POST("/service/update") // annotation used to post the data
    void postEditServiceData(@Body MultipartTypedOutput attachments, 
            Callback<RegistrationResponsModel> callback);

//这是我们发布文件的方式 multipartTypedOutput.addPart(&#34; profile_doc&#34;,new typedFile(&#34; multipart / form-data&#34;,postCurriculamFile));

//这是我们发布多张图片的方式

    for (int i = 0; i < images.size(); i++) {
        multipartTypedOutput.addPart("image[]", images.get(i));
    }