Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

okhttp multipart image upload with file name

i am trying to upload a image to server from an android phone. this is what i have done so far

  OkHttpClient client = new OkHttpClient();
            MultipartBuilder builder = new MultipartBuilder();


builder.type(MultipartBuilder.FORM).addPart(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestPackage.getJsonParam().toString()));
            for (int i = 0; i < requestPackage.getPics().size(); i++) {
                builder.addPart(RequestBody.create(MediaType.parse("image/png"/* + i*/), new File(URI.create(requestPackage.getPics().get(i)))));
            Log.i("image to upload",URI.create(requestPackage.getPics().get(i)).toString());
            }
            requestBody = builder.build();
     Request request = new Request.Builder().url(requestPackage.getUri()).post(requestBody).build();
            try {
                response = client.newCall(request).execute();
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    //            System.out.println(response.body().string());
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }

how do i add names to the different parts.because if there is no name(key) to them then how will server side guy store it?

like image 567
shreyas Avatar asked Nov 12 '14 13:11

shreyas


Video Answer


2 Answers

Get OkHttp 2.1, and use MultipartBuilder.addFormDataPart() which takes the filename as a parameter.

like image 198
Jesse Wilson Avatar answered Sep 25 '22 01:09

Jesse Wilson


The syntax seems to have changed a bit since the previous answers. I'm using OkHttp 3.2.0.

public void upload(String url, File file) throws IOException {
    RequestBody formBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", file.getName(),
            RequestBody.create(MediaType.parse("image/png"), file))
        .addFormDataPart("other_field", "other_field_value")
        .build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    Response response = this.client.newCall(request).execute();
}
like image 37
Bryant Kou Avatar answered Sep 25 '22 01:09

Bryant Kou