How to upload images to the server using retrofit 2 - android

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

Related

Cannot request a post using multipart

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());

'stream ended unexpectedly' error while Multipart Image Upload using Retrofit 2.0 - Android

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?

Upload list of objects to mysql using Retrofit Android

I have an ArrayList of custom objects, each with about 10 fields, that I already managed to upload to our server. The problem is that one of the fields is a String which contains a Base64-encoded string that I converted from a file, which the Retrofit Gson creater does not seem to like. This problem could be solved by just sending all the fields without the image, and then after that upload all the images using ftp, but it would be so much easier if I could just put the image in the object somehow.
Question: How can I send a Base64-encoded string as a field inside a custom object to a url using Retrofit?
#FormUrlEncoded
#POST("/UploadImages")
Call<ResponseBody> postImages(#Body ArrayListImage img);
//POJO CLASS
public class ArrayListImage {
#SerializedName("image")
#Expose
private ArrayList<String> image;
public ArrayListImage(ArrayList<String> image) {
this.image=image;
}
}
Below is the RequestBody code which i use to upload file using Retrofit:
RequestBody lRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part lFile = MultipartBody.Part.createFormData("file", file.getName(), lRequestBody);
MultipartBody.Part title = MultipartBody.Part.createFormData("title", file.getName());
MultipartBody.Part lFilenamebase64 = MultipartBody.Part.createFormData("filenamebase64", base64EncodedFileName);
To encode file name:
String base64EncodedFileName = Base64.encodeToString(file.getName().getBytes(Charsets.UTF_8), Base64.URL_SAFE | Base64.NO_WRAP);
I defined the api like:
#Multipart
#POST("/upload")
Observable<Response<ResponseBody>> uploadFile(#Part MultipartBody.Part file, #Part MultipartBody.Part title, #Part MultipartBody.Part base64EncodedFileName);
I hope it might help you.
//Convert Object list into json string.
Gson gson = new Gson();
String objListString = gson.toJson(objectList);
#FormUrlEncoded
#POST("********")
Call<JsonObject> sendObjectList(#Field("objListString") String objListString);
And at the web end parse string into json.
#enjoy

okhttp request / multipart image

Ok, before you start saying that it's a duplicate and so on...
I have tried all ways I found on slack / documentations and it didn't help me out at all...and I just can't figure out what the problem is
So, these are last 2 ways I tried to make the request
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
//RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), loadImageFile);
//MultipartBody.Part filePart = MultipartBody.Part.createFormData("picture", loadImageFile.getName(), reqFile);
//RequestBody filename =
RequestBody.create(MediaType.parse("text/plain"),loadImageFile.getName());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),
loadImageFile);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file",
loadImageFile.getName(), requestBody);
The commented parts is a way, and the other lines is the way I am doing it now..
Here I have the interface
#Multipart
#POST(RestClient.API_REGISTER_URL)
Call<ResponseBody> register(#Query("name") String name, #Query("email") String email,
#Query("password") String password, #Query("location") String location,
#Query("latitude") double latitude, #Query("longitude") double longitude,
#Query("gender") String gender, #Part MultipartBody.Part picture,
#Part("picture") RequestBody file,
#Query("device_uuid") String device_uuid, #Query("device_os") String device_os,
#Query("push_token") String push_token, #Query("api_key") String user);
To be honnest, I simply can't figure out why it is not working..the response body from the server is "The picture must be an image" which makes me think that somehow it doesn't recognise the file I am sending
Any help would be apreciated, thanks .
EDIT
I changed the code a lil bit, another way I was trying to make it, and still something is not ok with this request...
RequestBody req = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("picture", loadImageFile.getName(), RequestBody.create( MultipartBody.FORM, loadImageFile))
.build();
MultipartBody.Part part = MultipartBody.Part.createFormData("picture", loadImageFile.getName(), req);
I'm using this code to send image to server with okhttp
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody req = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("branchCode", branchCode)
.addFormDataPart("upload", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, file)).build();
Request request = new Request.Builder()
.url(URLs.UPLOAD_FILE)
.post(req)
.build();
Maybe problem occurs in your server side ?

Retrofit2 - Upload photo 500 Internal Server error

I want to upload a photo using Retrofit2, but I can't get rid of 500 Internal Server error. I also get the message "reduce of empty array with no initial value". When I retrieve the uploaded photos from the server, the photo is not there. I'm using Charles Web Debugging Proxy tool to check the response.
public static void postPhoto(String participantId, String photoPath) {
try {
File photo = new File(photoPath);
ApiEndpoints api = ApiProvider.getInstance().getApiInstance();
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), photo);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", photo.getName(), reqFile);
Call<ResponseBody> call = api.uploadPhoto(participantId, body);
call.execute();
} catch (Exception e){
e.printStackTrace();
}
}
API endpoint
#Multipart
#POST("participant/{id}/image")
Call<ResponseBody> uploadPhoto(#Path("id") String id, #Part MultipartBody.Part image);

Categories

Resources