Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] java – Upload file using both Multipart and JSON Key value pairs with Retrofit2

Posted on November 11, 2022 By

Solution 1 :

Works fine for me (it’s my code, just adapt it to your business logic):

Interface:

@Multipart
@POST("{projectName}/log")
Call<LogRp> uploadFile(
        @Path("projectName") String project,
        @PartMap Map<String, RequestBody> mp,
        @Part MultipartBody.Part file
        );

Service:

private MultipartBody.Part buildFilePart(File file, FileType type) {
    return MultipartBody.Part.createFormData("file", file.getName(),
            RequestBody.create(MediaType.parse(type.value.get()), file));
}

private Map<String, RequestBody> buildJsonPart(LogRq logRq) throws JsonProcessingException {
    return Collections.singletonMap("json_request_part", RequestBody.create(
            MediaType.parse("application/json"),
            new ObjectMapper().writeValueAsString(logRq))
    );
}

And then simply:

client.uploadFile(
                        project,
                        buildJsonPart(logRq),
                        buildFilePart(file, type)
                )

LogRp and LogRq are Response and Request POJOs.
ping me if help needed.

Solution 2 :

You can use VolleyMultipartRequest to upload File with text.

VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {


                String resultResponse = new String(response.data);
                try {
                    JSONObject result = new JSONObject(resultResponse);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                NetworkResponse networkResponse = error.networkResponse;
                String errorMessage = "Unknown error";
                if (networkResponse == null) {
                    if (error.getClass().equals(TimeoutError.class)) {
                        errorMessage = "Request timeout";
                    } else if (error.getClass().equals(NoConnectionError.class)) {
                        errorMessage = "Failed to connect server";
                    }
                } else {
                    String result = new String(networkResponse.data);
                    try {
                        JSONObject response = new JSONObject(result);
                        String status = response.getString("status");
                        String message = response.getString("message");

                        Log.e("Error Status", status);
                        Log.e("Error Message", message);

                        if (networkResponse.statusCode == 404) {
                            errorMessage = "Resource not found";
                        } else if (networkResponse.statusCode == 401) {
                            errorMessage = message + " Please login again";
                        } else if (networkResponse.statusCode == 400) {
                            errorMessage = message + " Check your inputs";
                        } else if (networkResponse.statusCode == 500) {
                            errorMessage = message + " Something is getting wrong";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Log.i("Error", errorMessage);
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("Some_text", "text");

                return params;
            }

            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                // file name could found file base or direct access from real path
                // for now just get bitmap data from ImageView
                params.put("pofile_pic", new DataPart("file_avatar.jpg", getFileDataFromDrawable(bitmap), "image/jpeg"));
                return params;
            }
        };
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(multipartRequest);

Problem :

Currently we are uoloading files (Video, Audio, Text etc..) by converting String bytes with simple JSON including some other values with their Key-Value pairs. Just like below:

READ  [FIXED] javascript - Is having different iOS bundle ID from android package name bad?
Powered by Inline Related Posts

Some header values:

{
    "header": {
        "geoDate": {
            "point": {
                "longitude": 77.56246948242188,
                "latitude": 12.928763389587403
            },
            "date": "2020-02-25T18:26:00Z"
        },
        "version": "1.35.00.001",
        "businessId": "178"
    }
}

and files info:

    JSONObject data = new JSONObject();
    data.put("name", params.name);
    data.put("mimeType", params.mimeType);
    data.put("fileSize", params.fileSize);
    data.put("inputData", params.data);

    requestJSON.put("data", data);

Here params.data is a simple conversion of bytes String bytes = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);

It’s working but we want to do it through Retrofit by sending the files through MultiPart to the server and which will improve the performance as well. But the problem is as it was in the JSON structure, the server can’t change its program and we (app) only have to do something which sends the file using Retrofit Multipart including other values and keys(inputData also).

I am searching for a way to do that. And I am wondering if we are able to send also, is the server has to change anything for the API structure like currently its accepting String for the bytes and we are going to change it to file for inputData.

Comments

Comment posted by Ranjit

Seems perfect. can we construct LogRp with the help of GSON?

Comment posted by jsonschema2pojo.org

Sure. You create your POJO class (LogRp). I use

Comment posted by Ranjit

Thanks for the reply. yeah, Volley is good, but we need it to do with Retrofit2 only as we have already done some other API changes with Retrofit.

Android Tags:android, file-upload, java, retrofit2

Post navigation

Previous Post: [FIXED] java – How to solve debug issue
Next Post: [FIXED] android – How to solve setting up this payment problem – paypal

Related Posts

[FIXED] android – This is taking an unexpectedly long time Android
[FIXED] java – Change color in second activity using button in main activity = crashes Android
[FIXED] android – How to Sort my Map Arraylist Alphabetically Android
[FIXED] android – App locale not change in OS version lower than Oreo Android
[FIXED] android – Getting empty values from GoogleFit API – Heart Rate Aggregate Android
[FIXED] It is possible to create a button by passing parameters in the XML android? Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What is the rising action in Julius Caesar?
  • How do you secure a rope to itself?
  • Does waterproof laminate scratch easily?
  • What makes a building prewar?
  • What can you learn in a month without alcohol?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme