I am trying to upload image with Retrofit library. This is how I am uploading:
Request Code:
@Multipart
@POS
For Retrofit 2.0 this worked for me
@Multipart
@Headers("Content-Type: application/json")
@POST("api/accounts/{id}/portrait")
Call<PortraitResponse> postPortrait(@Header("Authorization") String authorization, @Path("id") String id, @Part MultipartBody.Part file);
public void postPortrait(Uri uri) {
String auth = "Auth";
String id = "someId";
File file = new File(uri.getPath());
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("portrait", file.getName(), requestFile);
postPortraitCall = getAccountClient().postPortrait(auth, id, body);
postPortraitCall.enqueue(new Callback<PortraitResponse>() {
@Override
public void onResponse(Call<PortraitResponse> call, Response<PortraitResponse> response) {
if (response.isSuccessful()) {
// Success
} else {
// Failed
}
}
@Override
public void onFailure(Call<PortraitResponse> call, Throwable t) {
// Failed
}
});
}
I also had the similar problems and after few hours trying I finally built image uploading functionality to remote server.
To upload image you need to create the API properly and also need to pass the image properly. In Retrofit client you need to set up the image as followed:
String photoName = "20150219_222813.jpg";
File photo = new File(photoName );
TypedFile typedImage = new TypedFile("application/octet-stream", photo);
RetrofitClient.uploadImage(typedImage, new retrofit.Callback<Photo>() {
@Override
public void success(Photo photo, Response response) {
Log.d("SUCCESS ", "SUCCESS RETURN " + response);
}
@Override
public void failure(RetrofitError error) {
}
});
API setup:
@Multipart
@POST("/")
void uploadImage(@Part("file") TypedFile file, Callback<Photo> callback);
Remote Server Side PHP Code to handle the image:
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['file']['tmp_name'], $pic)) {
echo "posted";
}
If it helps any one please recognize me..thanks a lot..