Search code examples
androidimageretrofit2multipart

How to make MultipartBbody.Part request from cache image using retrofit


My image is cached at located:

file:///data/user/0/com.example.muhammadusman.project/cache/cropped1340954678061130725.jpg

how can i make the Multipart.body request for this interface:

 @Multipart
    @POST("/image/{name}")
    Call<Recognition> recognizeImage(
            @Path("name")String name,
            @Part MultipartBody.Part image);

Input to the Function

key="40"

imageName="cropped1340954678061130725.jpg"

path="file:///data/user/0/com.example.muhammadusman.project/cache/cropped1340954678061130725.jpg"

This is My Code: i am using this code to make the MultipartBody.Part object. But i am not able to make the object. Always program crash.

 public static MultipartBody.Part creatPartFromPath(String key,String imageName,String path){

        File file=new File(path);
        String mediaType= getMimeType(path);
        RequestBody intermediateFile=RequestBody.create(MediaType.parse(mediaType),file);
        return MultipartBody.Part.createFormData(key,imageName,intermediateFile);
    }

  public static String getMimeType(String url) {

        return url.substring(url.lastIndexOf(".") + 1);

    }

Solution

  • Github link for source code: https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

    Use this code:

    i have test this code this works fine. The link contain the whole source code. But i customize the file for you this will work fine for you.

    Problem Solution:

     String path=FileUtils1.getPath(getContext(),titleImageUri);
    

    now you path will be

    path="/data/user/0/com.example.muhammadusman.project/cache/cropped8174258068738559892.jpg"
    

    replace your previous path with this new path.

    public class FileUtils1 {
        private FileUtils1() {} //private constructor to enforce Singleton pattern
    
        /** TAG for log messages. */
        static final String TAG = "FileUtils";
        private static final boolean DEBUG = false; // Set to true to enable logging
    
        public static final String MIME_TYPE_AUDIO = "audio/*";
        public static final String MIME_TYPE_TEXT = "text/*";
        public static final String MIME_TYPE_IMAGE = "image/*";
        public static final String MIME_TYPE_VIDEO = "video/*";
        public static final String MIME_TYPE_APP = "application/*";
    
        public static final String HIDDEN_PREFIX = ".";
    
    
        public static File getFile(Context context, Uri uri) {
            if (uri != null) {
                String path = getPath(context, uri);
                if (path != null && isLocal(path)) {
                    return new File(path);
                }
            }
            return null;
        }
    
        public static boolean isLocal(String url) {
            if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
                return true;
            }
            return false;
        }
    
        public static String getPath(final Context context, final Uri uri) {
    
            if (DEBUG)
                Log.d(TAG + " File -",
                        "Authority: " + uri.getAuthority() +
                                ", Fragment: " + uri.getFragment() +
                                ", Port: " + uri.getPort() +
                                ", Query: " + uri.getQuery() +
                                ", Scheme: " + uri.getScheme() +
                                ", Host: " + uri.getHost() +
                                ", Segments: " + uri.getPathSegments().toString()
                );
    
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    
            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // LocalStorageProvider
    
                // ExternalStorageProvider
                 if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
    
                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
    
                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {
    
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    
                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
    
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
    
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[] {
                            split[1]
                    };
    
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
    
                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.getLastPathSegment();
    
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
    
            return null;
        }
    
        public static boolean isGooglePhotosUri(Uri uri) {
            return "com.google.android.apps.photos.content".equals(uri.getAuthority());
        }
    
    
        public static boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }
    
        public static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }
    
        public static String getDataColumn(Context context, Uri uri, String selection,
                                           String[] selectionArgs) {
    
            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {
                    column
            };
    
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    if (DEBUG)
                        DatabaseUtils.dumpCursor(cursor);
    
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }
    
        public static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }
    }