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?
Get OkHttp 2.1, and use MultipartBuilder.addFormDataPart()
which takes the filename as a parameter.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With