trna ha minh
trna ha minh

Reputation: 253

upload picture to server android

I have to capture image and upload it to server using retrofit2 My API

    @Multipart
    @POST("photo/")
    Call<NetWorkResponse<String>> uploadPhoto(@Header("Authorization") String token,
                                                @Part("category") String category,
                                                @Part MultipartBody.Part photo);

My method to upload photo

public static void uploadPhoto(String nfToken, String category, File photoFile) {


        RequestBody filePart = RequestBody.create(MediaType.parse("image/jpeg"), photoFile);

        MultipartBody.Part file = MultipartBody.Part.createFormData("photo", photoFile.getName(), filePart);

        Call<NetWorkResponse<String>> call = nfApi.uploadPhoto(nfToken, category, file);
        call.enqueue(new Callback<NetWorkResponse<String>>() {
            @Override
            public void onResponse(Call<NFNetWorkResponse<String>> call, Response<NetWorkResponse<String>> response) {

                if (response.isSuccessful()) {
                    NetWorkResponse<String> netWorkResponse = response.body();

                } else {

                }
            }

            @Override
            public void onFailure(Call<NetWorkResponse<String>> call, Throwable t) {

            }
        });
    }

My photo file Uri: file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

When I upload the file to server, I got error Bad Request, code 400. which may indicate that my param is wrong but I am quite sure there is nothing wrong with that. I guess sth is wrong with the picture, sth is wrong with MediaType.parse("image/jpeg")

Instead that should be:

 File f = new File(mCurrentPhotoPath);
 Uri pictureUri = Uri.fromFile(f);
 String contentType = getContentResolver().getType(pictureUri);
 MediaType.parse(contentType)

But the problem is that the Uri path is file:// not content:// so contentType is null

Any idea what's wrong when I upload photo to the server

Upvotes: 1

Views: 170

Answers (1)

shahid17june
shahid17june

Reputation: 1577

Instead of Photo file URL file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

Pass this one /storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

Upvotes: 0

Related Questions