I am trying to Upload file along with JSON
post body. I have tried something like this:
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("data", uploadFileName[1], RequestBody.create(MEDIA_TYPE_JPEG, file))
.addFormDataPart("name", uploadFileName[1])
.addFormDataPart("body",postBody)
.build();
NOTE: Above code works if I want to upload file without post body by removing
.addFormDataPart("body",postBody)
also I have tried to create ByteOutputArray of both file and post body and tried to create a ResquestBody
.
Something like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment;filename=\"" + uploadFileName + "\"\r\n").getBytes("UTF-8"));
baos.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes("UTF-8"));
byte[] buffer = new byte[102400];// 100KB
int read = imageInputStream.read(buffer);
while (read >= 0) {
baos.write(buffer);
read = imageInputStream.read(buffer);
}
baos.write(("\r\n").getBytes("UTF-8"));
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment; name=\"" + fileNameText + "\"\r\n\r\n").getBytes("UTF-8"));
baos.write((postData).getBytes("UTF-8"));
baos.write(("\r\n").getBytes("UTF-8"));
baos.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
baos.flush();
MediaType MEDIA_TYPE_JPEG = MediaType.parse(fileType);
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPEG,baos.toByteArray());
But nothing is working. Please help.