Created
August 8, 2017 09:43
-
-
Save deepakpk009/ba7414892062ec69aefad42f2dc29b56 to your computer and use it in GitHub Desktop.
How to POST Form data with multiple attachments using Retrofit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface FormUploadService { | |
@Multipart | |
@POST("<post-url-endpoint>") // the post url endpoint | |
Observable < String > postFormWithAttachments( | |
@Header(AppConstants.KEY_AUTH) String authKey, // auth key, if required | |
@PartMap Map < String, RequestBody > params); // our form data map | |
} | |
public void postForm(String authKey, | |
FormPostObject formPostObject, | |
List < File > attachments, | |
Callback < ResultObject > resultObjectCallback) { | |
Map < String, RequestBody > map = new HashMap < > (); | |
map.put("description", toRequestBody(formPostObject.getDescription())); | |
map.put("subject", toRequestBody(formPostObject.getSubject())); | |
map.put("email", toRequestBody(formPostObject.getEmail())); | |
if (attachments != null && attachments.size() > 0) { | |
for (int i = 0, size = attachments.size(); i < size; i++) { | |
File file = attachments.get(i); | |
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); | |
// replace the 'attachments[]' with your expected form data name | |
map.put("form-data; name=\"attachments[]\"; filename=\"" + file.getName() + "\";", fileBody); | |
} | |
} | |
formUploadService.postFormWithAttachments(authKey, map).enqueue(resultObjectCallback); | |
} | |
private RequestBody toRequestBody(String value) { | |
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value); | |
return body; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment