【问题标题】:"Retrofit" multiple images attached in one multipart request在一个多部分请求中“改造”多个图像
【发布时间】:2014-10-04 14:55:22
【问题描述】:

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

以下代码仅适用于单个图像:

界面:

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

【问题讨论】:

    标签: android multipart retrofit


    【解决方案1】:

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

    这是参考 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

    更新

    MultipartTypedOutput 在 Retrofit 2.0.0-beta1 中不再存在

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

    【讨论】:

    • 这对我来说非常有用,因为我需要具有相同名称但值不同的部件。类似于数组,但名称不能带有“[]”和一个新部分。
    • 就像一个魅力。谢啦!!注意:使用 Body 和 POST 时不要忘记删除 @Multipart 注解!
    • 在我的情况下,MultipartTypedOutput 运行速度比 part 我不知道为什么会发生这种情况你能告诉我吗??
    • 请告诉我你是如何挑选图像的
    • 任何改造 2 的解决方案,因为这不起作用?
    【解决方案2】:
    //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("profile_doc",new TypedFile("multipart/form-data", postCurriculamFile));

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

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

    【讨论】:

    • 看起来很有趣,但是这个 postCurriculamFile 是什么方法?我使用通常的画廊意图来选择每张图片,你能指点我吗
    • postCurriculamFile 是文档的路径,路径文件通过 Intent。如果您发布的图像意味着不需要此行。 if (fileType.equalsIgnoreCase("application/pdf") || fileType.equalsIgnoreCase("doc")) { Utils.savePreferences(context, "postservicefile", path); }
    • 感谢重播实际上我创建了一个对参数的凌空请求,并在其中响应了一个对图像的改造请求,它工作正常,但它是一个安全的代码?
    • 实现它看起来不错,而且它的代码安全,但优化角度更适合复古。您可以同时实现图像和参数请求。
    • 很难理解,我很着急,它不能单独工作,或者我做不到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2018-02-16
    • 1970-01-01
    • 2018-04-12
    • 2021-01-12
    相关资源
    最近更新 更多