I am using retrofit to upload image (base64 String) with data to server. Now i can send video or image depending on condition so i wanted to know how is it possible to upload it since video is much heavier. How do i upload video on retrofit with my other data. My previous method to send data with image was:
Map<String, Object> params = new HashMap<>();
params.put(URLParam.USER_ID, user.getId());
params.put(URLParam.MEDIA, mBase64String);
#Headers({"Accept: application/json", "Content-Type:application/json"})
#POST("/v1/address")
Call<ResponseBody> uploadPost(#Body Map<String, Object> params);
How do i send video now
Retrofit interface method would look like this..
#Multipart
#POST("/your url/")
Call<ResultObject> uploadVidToServer(#Part MultipartBody.Part video);
Send the file in multipart so that you can handle the progress dialog ...for better UI
Then make the retrofit call like this :-
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
pathToVideoFile is the string path of your file
Finally make the call
Call<ResultObject> uploadVideo = vInterface.uploadVidToServer(vFile);
uploadVideo .enqueue........
Remember :-
Create the requestBody from your VideoFile that you want to upload.
Create MutlipartBody.Part object from the RequestBody object.
Then make the call.
Related
I know it is not wise to use multipart for simple text authentication. but I need to use it with api provided to me.
I tried all the methods possible.
It's working fine with postman
but not with retrofit 2
request type details
request type details
code used
tried
//RequestBody requestNameRq = RequestBody.create(MediaType.parse("text/plain"),serviceNameValue);
//RequestBody requestAmountRq = RequestBody.create(MediaType.parse("text/plain"),serviceAmountValue.toString());
/* Create Request Body */
//MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
// .addFormDataPart("service",serviceNameValue)
// .addFormDataPart("amount", String.valueOf(serviceAmountValue));
//RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
// .addFormDataPart("service",serviceNameValue)
// .addFormDataPart("amount",serviceAmountValue.toString()).build();
//MultipartBody.Part multipartRequestBody = MultipartBody.Part
// .createFormData("service",serviceNameValue)
// .createFormData("amount",serviceAmountValue.toString());
//MultipartBody multipartBody = builder.build();
Code for Apiservice
#POST("services")
Call<AddServiceResponse> addService(#Header("Authorization") String authToken,
//#Body MultipartBody body);
#Part("service") RequestBody service,
#Part("amount") RequestBody amount);
//#Part("service") String service,
//#Part("amount") String password);
//#Part("service") RequestBody service,
//#Part("amount") RequestBody amount);
}
Please try to add
#Multipart
before
#POST("services")
Modify your ApiService class
#Multipart
#POST("services")
Call<AddServiceResponse> addService(
#Header("Authorization") String authToken,
#Part("service") MultipartBody.Part service,
#Part("amount") MultipartBody.Part amount);
Then create MultipartBody
MultipartBody.Part serviceBody = MultipartBody.Part.createFormData("service", "Somethin2");
MultipartBody.Part amountBody = MultipartBody.Part.createFormData("amount", "2344");
Then call
apiService.addService(serviceBody, amountBody);
I am executing a post type request using Multipart. The problem is because I keep getting two errors
1) 500
2) 422 Unprocessable Entity
Everything works in the postman
Api only accepts music files.So I added a default file so as not to constantly choose a new one
RequestBody body =
RequestBody.create(MediaType.parse("audio/type"),file);
MultipartBody.Builder builder = new
MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addPart(body);
GeoService.saveSound(builder.build(), SoundResponseCallback,
getAuthToken());
and my interface which
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part("audio[file] ; filename=audio.mp3")RequestBody file,
#Query("auth_token") String authToken);
I would appreciate any help.
and I found it Send file to server via retrofit2 as object
You must send MultipartBody.Part type of parameter in your API
Try this:
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part MultipartBody.Part file,
#Query("auth_token") String authToken);
Change this
#Part("audio[file] ; filename=audio.mp3")RequestBody file,
to
#Part MultipartBody.Part audioFile,
Also make sure that you have enabled the necessary READ WRITE storage permissions
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part MultipartBody.Part audioFile,
#Query("auth_token") String authToken);
and
MultipartBody.Part body = MultipartBody.Part.createFormData("audio/type", file);
GeoService.saveSound(body, SoundResponseCallback,
getAuthToken());
I am using Retrofit 2.0 for image upload to server in Android. Following is the interface code.
#Headers("Content-Type: multipart/form-data; boundary=MyMediaFormBoundary")
#Multipart
#POST("api/media/upload/v1")
Call<MyResponse> uploadMedia(#Header("authToken") String authToken,
#Part("media_file\"; filename=\"media_file.jpg\" ") RequestBody filePart,
#Part("media_format") RequestBody format,
#Part("media_library_id") RequestBody noteId,
#Part("media_title") RequestBody title);
Here is my code to create request body params
File file = new File(mediaFileUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody formatBody = RequestBody.create(MediaType.parse("text/plain"), format);
RequestBody titleBody = RequestBody.create(MediaType.parse("text/plain"), title);
RequestBody idBody = RequestBody.create(MediaType.parse("text/plain"), id + "");
When I call my interface method with above parameters, I am getting error 'steam ended unexpectedly' and I am wondering what exactly I am doing wrong.
I also tried using MultipartBody.Part object of retrofit in above interface but still same result.
Following are the links which I used for reference:
first link
second link
Note: I doubt it is related to bad request but I am not getting much help from backend team and it is working on iOS. The only info I have is server side is fetching media file against key 'media_file' but I am wondering where to use it.
If you are sending image then why the media type is text/plain?
I have to upload an image to server using Retrofit2.
Everything has worked fine at first, but after I re-check it before the release the API failed that can't upload the image but still works using postman!
My code is :
MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image",
image.getFilename(), RequestBody.create(MediaType.get(image.getMimeType()), image.getFile()));
RequestBody sessionPart = RequestBody.create(MultipartBody.FORM, sessionToken);
RequestBody userIdPart = RequestBody.create(MultipartBody.FORM, userId);
RequestBody pictureTypePart = RequestBody.create(MultipartBody.FORM, pictureType.pictureTypeValue());
return dubaingNetwork.uploadProfilePic(accessToken,userIdPart,sessionPart,imagePart,pictureTypePart);
My api interface is:
#Multipart
#POST(Urls.UPLOAD_PROFILE_PIC)
Observable<UploadProfilePicResponse> uploadProfilePic(#Header(ACCESS_TOKEN_FIELD_NAME) String accessToken,
#Part(USER_ID_FIELD_NAME) RequestBody userId,
#Part(SESSION_TOKEN_FIELD_NAME) RequestBody sessionToken,
#Part MultipartBody.Part image,
#Part("image_type") RequestBody pictureType);
Edit: I tried to convert it to urlencoded type with the image converted to string Base64 and the parameters as a field but still the same error on phone and in postman still works, so I don't think it's a server-side error
How to add multiple images/files on a same parameter along with other textual data using retrofit?
Single image is uploading perfectly using following interface
#Multipart
#POST("/users/updateProfile/")
public void updateProfileWithImage(
#Part("user_id") TypedString first_name,
#Part ("image") TypedFile image,
Callback<WebResponse> callback);
You can use the #MultiPart Post with #PartMap as parameter
Map<String, TypedFile> files = new HashMap<String, TypedFile>();
files.put("my file number one", new TypedFile("image/jpg", new File(filename)));
files.put("my file number two", new TypedFile("image/jpg", new File(filename)));
apiInterface.updateProfileWithImage("first name here", files);
private interface ApiInterface{
#Multipart
#POST("/users/updateProfile/")
Response updateProfileWithImage(
#Part("user_id") TypedString first_name,
#PartMap Map<String,TypedFile> Files
);
}
Retrofit 2.0 + OkHttp 3
Interface declaration:
#POST("postpath")
Call<Void> upload(#Body MultipartBody filePart);
Creating MultiPartBody:
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
then for each file(you can also add custom fields)
requestBodyBuilder.addFormDataPart("extraImage[]", "photo.jpg",
RequestBody.create(MediaType.parse("image/jpeg"), byteArrayOrFile));
and finally
api.upload(requestBodyBuilder.build());
P.S. you can add custom form fields (for example client.name) to the same form with
requestBodyBuilder.addFormDataPart("client[name]", null, RequestBody.create(MediaType.parse("text/plain"), name))
or
requestBodyBuilder.addFormDataPart("client[name]", name))
Retrofit 1.9:
You can use MultipartTypedOutput to post variable number of multi-part parameters.
In addition to François' answer, to post multiple images with the same / repeating field name(as an array) in retrofit you can use MultipartTypedOutput
Method signature:
#POST("/postpath")
SomeResponse upload(#Body MultipartTypedOutput output);
Usage:
MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
multipartTypedOutput.addPart("mainImage", new TypedFile("image/jpeg", mainImage));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file1));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file2));
upload(multipartTypedOutput);
Square brackets
Please note that some server side frameworks(Rails) typically require square brackets(i.e. extraImage[] instead of extraImage), others don't (Spring MVC).