android - Retrofit 2 带数据的多部分图像上传

标签 android retrofit2 image-uploading multipart

大家好,我想通过 Retrofit2 发布图像和其他数据。 我正在发送带有一张图像的数据。

All the other info is storing but my image is not storing.while i am testing with postman, it works.

enter image description here

请指导我代码中缺少的地方

这是有效的 postman 代码 fragment

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType, "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\ntest6@gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n123456\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nTest\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"phone\"\r\n\r\n1234567890\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"image\"; filename=\"03.JPG\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
  .url("https://"url"/api/v1/sign-up")
  .post(body)
  .addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
  .addHeader("cache-control", "no-cache")
  .addHeader("postman-token", "2dd038d9-5f52-fcd0-9331-445eaf35c230")
  .build();

Response response = client.newCall(request).execute();

postman 请求图片如下:

enter image description here

这是我的 Retrofit api

    @Multipart
    @POST("sign-up")
    Call<SignUpResponse> getSignUpResponse(
            @Part("email") RequestBody email,
            @Part("password") RequestBody password,
            @Part("name") RequestBody name,
            @Part("phone") RequestBody phone,
            @Part MultipartBody.Part image
            //@Part("image") RequestBody image // i have thried them both but they didnt work
            //@Part("image\"; filename=\"pp.jpg\" ") RequestBody image
    );

这是我的客户区:

private RetrofitClient() {

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);  // <-- this is the important line!

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();
}

这是我提出请求的部分:

RequestBody namePart = RequestBody.create(MultipartBody.FORM, "nameasd");
RequestBody emailPart = RequestBody.create(MultipartBody.FORM, "emailasd@gmai.com");
RequestBody mobilePart = RequestBody.create(MultipartBody.FORM, "123456623");
RequestBody passwordPart = RequestBody.create(MultipartBody.FORM, "123456123");
//String filepath = "/storage/0403-0201/DCIM/Camera/20180926_203219.jpg"; this is the image source
File file = new File(filepath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image",file.getName(),reqFile);

Call<SignUpResponse> call = RetrofitClient.getInstance().getApi().getSignUpResponse(emailPart, passwordPart, namePart, mobilePart, body);
                call.enqueue(new Callback<SignUpResponse>() {
                    @Override
                    public void onResponse(Call<SignUpResponse> call, Response<SignUpResponse> response) {
                        progressDialog.dismiss();
                        Log.d(TAG, "onResponse: "+response.body());
                        Log.d(TAG, "onResponse: meta: " + response.body().getMeta().getStatus());
                    }
                    @Override
                    public void onFailure(Call<SignUpResponse> call, Throwable t) {
                        Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "onFailure: "+t.getMessage());
                    }
                });

这是我获取数据的代码

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // get selected images from selector
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                mResults = data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);
                imagePath = mResults.get(0);
                Glide.with(SignupActivity.this)
                        .load(mResults.get(0))
                        .into(profileImage);
              }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

I even set it on a view and that works...

最佳答案

我们在 Postman 中测试 api...所以我的 Create Post Answer 包括(所有动态)

  • Headers
  • Simple Strings
  • Single Image
  • Array Of Images
  • Array Of Categories
  • Array Of Features

几乎所有的东西

下面是用于api测试的Postman镜像... You will get clear concept of request

  • Headers Image

enter image description here

所以对于这个... 下面是我的 Api...

@POST("post-create")
    Call<PostCreateResponse> getPostCreateBodyResponse(
            @Header("Accept") String accept,
            @Header("Authorization") String authorization,
            @Body RequestBody file
    );

现在改造客户区--->

private Retrofit retrofit;

// This is Client
private RetrofitClient() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.connectTimeout(100, TimeUnit.SECONDS);
        httpClient.readTimeout(100,TimeUnit.SECONDS);
        httpClient.writeTimeout(100,TimeUnit.SECONDS);
        httpClient.addInterceptor(logging);  // <-- this is the important line!

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
    }

This is the way I Made the Request...

/*
     * -------------- Retrofit post Create single featured Image Working with MultipartBody -----------
     * */

    progressDialog.show();

    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    builder.addFormDataPart("title", "3 room Current Free")
            .addFormDataPart("location", "Dhaka")
            .addFormDataPart("latitude", "23.7515")
            .addFormDataPart("longitude", "90.3625")
            .addFormDataPart("condition", "1")
            .addFormDataPart("rent_amount", "123456")
            .addFormDataPart("is_negotiable", "0")
            .addFormDataPart("available_from", "2018-10-15");

    // Categories
    for (int categoryId : categories) {
        builder.addFormDataPart("categories[]", String.valueOf(categoryId));
    }
    // Features
    for (Integer featureId : features) {
        builder.addFormDataPart("features[]", String.valueOf(featureId));
    }

    // featured Image
    if (photoPaths.get(0) != null) {
        File featured_image = new File(photoPaths.get(0));
        if (featured_image.exists()) {

// If you want to use Bitmap then use this

            Bitmap bmp = BitmapFactory.decodeFile(featured_image.getAbsolutePath());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 30, bos);

            builder.addFormDataPart("featured_photo", featured_image.getName(), RequestBody.create(MultipartBody.FORM, bos.toByteArray()));


// If you want to use direct file then use this ( comment out the below part and comment the above part )

            //builder.addFormDataPart("featured_photo", featured_image.getName(), RequestBody.create(MultipartBody.FORM, featured_image));
        }
    }

    // Images
    for (String photoPath : photoPaths) {
        if (photoPath != null) {
            File images = new File(photoPath);
            if (images.exists()) {
                builder.addFormDataPart("images[]", images.getName(), RequestBody.create(MultipartBody.FORM, images));
            }
        }
    }

    RequestBody requestBody = builder.build();
    Call<PostCreateResponse> call = RetrofitClient.getInstance().getApi().getPostCreateBodyResponse(Accept, Authorization, requestBody);
    call.enqueue(new Callback<PostCreateResponse>() {
        @Override
        public void onResponse(Call<PostCreateResponse> call, Response<PostCreateResponse> response) {
            progressDialog.dismiss();
            Log.d(TAG, "onResponse: response code: retrofit: " + response.code());
        }

        @Override
        public void onFailure(Call<PostCreateResponse> call, Throwable t) {

        }
    });

    /*
     * ---------------- Retrofit post Create single featured Image Working with MultipartBody----------------
     * */

希望这对大家有所帮助...谢谢

关于android - Retrofit 2 带数据的多部分图像上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553210/

相关文章:

android - 一种从字符串中删除特定字符的方法? ( Kotlin )

javascript - 使用 "upload"按钮将多个图像上传到页面时出现问题...

java - Android CursorAdapters、ListViews 和后台线程

android - 将多个参数传递给 RecyclerView

android - Repository 方法在 Asynchronous Retrofit 调用中设置 LiveData 值

android - Android 12 中的异常

c# - 无法将 HttpPostedFileBase 对象转换为字节数组

php - 使用 CakePHP 3.2 上的 cakephp-upload 插件,图像不会保存到 photo_dir 文件夹中

android - 集成 HalpStack 后生成签名的 APK 警告即将到来

java - 无法在调用拦截 Android 应用程序中阻止号码不以“+91”开头的联系人