【问题标题】:Retrofit 2.0.2 image upload using multipartRetrofit 2.0.2 使用多部分上传图片
【发布时间】:2016-11-24 12:59:22
【问题描述】:

我是 Retrofit 的新手我想上传具有不同参数的单张图片,例如姓名、dob、mobile。 我不知道我错在哪里,请指导我。我关注这个LINK

这是我的代码

界面

 @Multipart
    @POST("signup")
    Call<ResponseBody> getSignup(@Part("name") RequestBody name, @Part("email") RequestBody email, @Part("dob") RequestBody dob, @Part("phone") RequestBody phone, @Part("IMEI") RequestBody IMEI, @Part MultipartBody.Part file);

上传代码

 // create RequestBody instance from file
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);

                // MultipartBody.Part is used to send also the actual file name
                MultipartBody.Part body =
                        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

                RequestBody name =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_name.getText().toString());

                RequestBody email =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_email.getText().toString());

                RequestBody dob =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_dob.getText().toString());

                RequestBody mobile =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_mobile.getText().toString());


                RequestBody imei =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), IMEI);

                Call<ResponseBody> responseBodyCall = apiInterface.getSignup(name, email, dob, mobile, imei, body);
                responseBodyCall.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                        String response_two = response.body().toString();

                        Log.i(TAG, "onResponse: " + response_two);
//                        startActivity(new Intent(this, OTPActivity.class));
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e("Upload error:", t.getMessage());
                    }
                });

【问题讨论】:

  • 你的问题是什么?
  • 我不想上传多个文件,我只想发送一个文件。
  • 我无法上传具有不同参数的文件,例如手机、姓名、imei 等。
  • 您尝试使用一张图片吗?这有效吗
  • 不,我没试过吗??

标签: android retrofit2


【解决方案1】:

Retrofit 2.0 以后试试这个答案

@Multipart
@POST("/service/users/add_user")
Call<AddUsersModel> addUser(@Part("user_name") RequestBody userName, @Part("user_last_name") RequestBody lastName, @Part("user_password") RequestBody password,
                               @Part("user_email") RequestBody email, @Part("user_mobile") RequestBody mobile, @Part MultipartBody.Part user_profile);

MulitpartBody.Part转换的文件路径

   MultipartBody.Part profileImageBody = null;
        RequestBody reqFile = null;
        try {
            String filePath = CameraIntentUtil.getFIlePath();
            Log.d(TAG, "createAccount: filePath:" + filePath);
            if (filePath != null) {
                File file = new File(filePath);

                reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                // "user_profile" is my post request key
                profileImageBody = MultipartBody.Part.createFormData("user_profile", file.getName(), reqFile);
            }
        } catch (Exception e) {
            Log.e(TAG, "createAccount: ", e);
        }

字符串到RequestBody的转换

public static RequestBody stringToRequestBody(String data) {
    return RequestBody.create(MediaType.parse("multipart/form-data"), data);
}

很晚的答案..但我希望它至少对任何人都有帮助

【讨论】:

    【解决方案2】:

    这是我的 POST 多部分示例

    @Multipart
    @POST("/api/register?platform=android")
    Call<Register> register(@Part("photo\"; filename=\"photoName.png\" ") RequestBody photo,
                                         @Part("name") RequestBody name,
                                         @Part("phoneNumber") RequestBody phoneNumber,
                                         @Part("password") RequestBody password,carColor,
                                         @Query("language") String language);
    

    【讨论】:

    • 查询在改造 2.0.2 中不起作用,只有我们可以发送部件类型
    • 我有 - 编译 'com.squareup.retrofit:retrofit:2.0.0-beta2' 有什么不同吗?
    • 啊抱歉!我不知道
    【解决方案3】:

    您需要为图像添加相同的类型,也可以在这里查看它是如何工作的, 这也适用于多个图像。

    @Multipart
    @POST(ApiConstants.EDIT_REQUEST)
    Observable<CommonModel> editRequest(@Part("requestid") RequestBody requestid, @PartMap() Map<String, RequestBody> mapFileAndName);
    
    
    RequestBody requestid1 = RequestBody.create(MediaType.parse("text/plain"), requestid);
    
    Map<String, RequestBody> files = new HashMap<>();
        for (int i = 0; i < mList.size(); i++) {
            String key = "package_image[" + String.valueOf(i) + "]";
            files.put("" + key + "\"; filename=\"" + key + ".png", getRequestFile(new File(mList.get(i).getImagePath())));
    }
    
    
    
    private RequestBody getRequestFile(File file) {
    
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        return fbody;
    
    }
    

    更多详情您可以访问here

    【讨论】:

      【解决方案4】:

      在改造 2.3.0 上测试

      1. 创建interface

        @Multipart
        @POST("edit_profile")
        Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> 
         map);
        
      2. 致电您的Activity

                     Retrofit retrofit=new Retrofit.Builder()
                    .baseUrl(getString(R.string.api_coolpool))
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
                    File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn 
                    Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
                     String convert_File_2String= String.valueOf(file);
                     String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
        RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
        Map<String, RequestBody> map = new HashMap<>();
        map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
        map.put("firstname", name);
        map.put("user_id", id);
        map.put("lastname",lastname);
        
        Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
        tokenResponseCall.enqueue(new Callback<TokenResponse>() {
            @Override
            public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
                 if (response.isSuccessful())
                Log.e("Success", new Gson().toJson(response.body()));
            else
                Log.e("unSuccess", new Gson().toJson(response.errorBody()));
        }
        
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        
            @Override
            public void onFailure(Call<TokenResponse> call, Throwable throwable) {
                Log.e("172","><<>>"+throwable);
        
            }
        });
        

      【讨论】:

        猜你喜欢
        • 2015-02-22
        • 2014-06-14
        • 2014-08-01
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-25
        • 1970-01-01
        相关资源
        最近更新 更多