Retrofit 2 Multipart image upload with data

后端 未结 5 683
陌清茗
陌清茗 2020-12-30 16:37

Hello everyone I want to post image and other data through Retrofit2. I am sending data with one image.

All the other info is storing but my image is

5条回答
  •  长发绾君心
    2020-12-30 16:54

    We test api in Postman... So my Create Post Answer includes (all Dynamic)

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

    Almost all things

    Below is the Postman image for api testing...

    • Headers Image

    So for this ... Below is my Api...

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

    Now Retrofit Client area--->

    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 call = RetrofitClient.getInstance().getApi().getPostCreateBodyResponse(Accept, Authorization, requestBody);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                progressDialog.dismiss();
                Log.d(TAG, "onResponse: response code: retrofit: " + response.code());
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
    
            }
        });
    
        /*
         * ---------------- Retrofit post Create single featured Image Working with MultipartBody----------------
         * */
    

    I hope this will help you all... thanks

提交回复
热议问题