How do I upload Bitmap to web server using Okhttp?

Asked 1 years ago, Updated 1 years ago, 134 views

I'm going to upload a picture using php

I'm going to take the photo selected by the camera or gallery and resize it with bitmap and upload it on the server

Here we go. Give me a tip <

okhttp bitmap

2022-09-22 12:58

1 Answers

The basic appearance of the code that receives the image file as an input and sends it to the server seems to be as follows. Some parts need to be modified according to the environment, so please refer to the code and implement it.

public static String uploadPhoto(File file) {
    try {
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("photo", "photo.png", RequestBody.create(MediaType.parse("image/png"), file))
            .build();

        String url = "http://...";
        okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        return response.body().string();
    } } catch (UnknownHostException | UnsupportedEncodingException e) {
        ...
    } } catch (Exception e) {
        ...
    }
    return null;
}


2022-09-22 12:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.