Retrofit Multipart Upload Image failed

荒凉一梦 提交于 2019-11-28 07:50:34
techhunter

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..

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!