Android Retrofit+Rxjava实现上传头像

首先肯定先要在Retrofit的Service里定义参数

//上传头像

@Multipart
@POST(HttpUrlUtils.UPLOADING_HEAD_URL)
Observable setHead(@Part MultipartBody.Part image, @Header("userId") int userId,
 @Header("sessionId") String sessionId);

第一个参数是上传的头像,用Part注释声明 image是往后台提交的名字 userid和sessionId应该都知道.

//点击头像,进行选择更换

    My_head.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.head_layout, null);
            popupWindow = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, 
            ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setContentView(view);
            popupWindow.setBackgroundDrawable(new ColorDrawable());
            popupWindow.setOutsideTouchable(true);
            popupWindow.setClippingEnabled(true);
            popupWindow.setTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    popupWindow.dismiss();
                }
            });
            Camera = (Button) view.findViewById(R.id.Camera);
            Photo = (Button) view.findViewById(R.id.Photo);
            cancel = (Button) view.findViewById(R.id.cancel);
            //选择拍照.拍照上传头像暂时不好使
            Camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    intent.addCategory("android.intent.category.DEFAULT");
                    startActivityForResult(intent, 0);
                }
            });
            //点击相册,选择图片
            Photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 1);
                }
            });
            popupWindow.showAsDropDown(v, 0, 0);
        }
    });
    //这是上传头像的P层
    headPersenter = new HeadPersenter(this);

调用相机相册肯定要执行Activity回调

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
   		//调用相机的回调
        case 0:
            Bitmap bitmap = data.getParcelableExtra("data");
            FrescoUtils.setTo(headPath, MyBckground);
            popupWindow.dismiss();
            break;
         //调用相册的回调
        case 1:
        	//判断是不是选中图片了
            if (resultCode == Activity.RESULT_OK) {
                final int userId = SpUtil.getInt("userId", -1);
                String sessionId = SpUtil.getString("SessionId", "");
                Uri uri = data.getData();
                if (uri!=null){
                	//用一个工具类获取图片的绝对路径,我会粘到下方
                    String path = ImageUtil.getPath(getActivity(), uri);
                    if (path!=null){
                    	//转换为file类型
                        File file = new File(path);
                        //调用P层
                        headPersenter.setHead(userId, sessionId, file);
                        popupWindow.dismiss();
                    }
                }
            } else {
                Toast.makeText(App.mContext, "取消选择", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
            break;
    }
}

P层的代码

public void setHead(int userId, String sessionId, File file){
    headModel.setHead(userId, sessionId, file, new HeadCallBack() {
        @Override
        public void OnSetHeadSucess(HeadBean headBean) {
            headView.OnSetHeadSucess(headBean);
        }

        @Override
        public void OnSetHeadFailer(String msg) {
            headView.OnSetHeadFailer(msg);
        }
    });
}

M层的代码

public void setHead(int userId, String sessionId, File file, final HeadCallBack headCallBack) {
    Draww api = RetrofiApi.getInstance().creatApi(Draww.class);
    //进行类型转换,因为在RetrofitService定义的是@Part MultipartBody.Part,所以要转成这样的格式
    RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    MultipartBody.Part image = MultipartBody.Part.createFormData("image", file.getName(),requestBody);
    //然后再把image传过去
    api.setHead( image,userId, sessionId).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    headCallBack.OnSetHeadFailer(e.getMessage());
                }

                @Override
                public void onNext(HeadBean headBean) {
                    headCallBack.OnSetHeadSucess(headBean);
                }
            });
}

获取图片路径的工具类,请自行拿取

//代码版,直接复制
public class ImageUtil {
public static Intent getGalleryIntent(Intent intent)
{
    /**19之后的系统相册的图片都存在于MediaStore数据库中;19之前的系统相册中可能包含不存在与数据库中的图片,所以如果是19之上的系统
     * 跳转到19之前的系统相册选择了一张不存在与数据库中的图片,解析uri时就可能会出现null*/
    if (Build.VERSION.SDK_INT < 19) {
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
    } else {
        intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
    }
    return intent;
}

/**
 * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
 * 可以用在  解析 uri 数据的地方(相册回传数据)
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri)
{

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
    {
        // 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];

            }

        }
        // 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 getDataColumn(context, uri, null, null);

    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme()))
    {
        return uri.getPath();

    }
    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */

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())
        {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);

        }

    }
    finally
    {
        if (cursor != null)
        {
            cursor.close();
        }

    }
    return null;

}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */

public static boolean isExternalStorageDocument(Uri uri)
{
    return "com.android.externalstorage.documents".equals(uri.getAuthority());

}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */

public static boolean isDownloadsDocument(Uri uri)
{
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());

}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */

public static boolean isMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".equals(uri.getAuthority());

}

}

你可能感兴趣的:(原创)