简单的Retrofit上传头像

1、Contrats

	public static final String BASEURL = "http://120.27.23.105/";
    public static final String UPLOAD = "file/upload";

2、MyApiService

	@Multipart
    @POST
    Observable upLoadImage(@Url String url, @QueryMap Map map, @Part MultipartBody.Part file);

3、工具类

public class RetrofitUtils {
    private MyApiService myApiService;
    private OkHttpClient okHttpClient;

    public RetrofitUtils() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30,TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Contrats.BASEURL)
                .client(okHttpClient)
                .build();

        myApiService = retrofit.create(MyApiService.class);
    }

    public static RetrofitUtils getInstance(){
        return RetrfitHolder.retrofitUtils;
    }

    private static class RetrfitHolder{
        private static final RetrofitUtils retrofitUtils = new RetrofitUtils();
    }

	//上传头像
    public void upLoadImage(String url, Map map, MultipartBody.Part file, final CallBacks callBacks){
        Observer observer = new Observer() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if(callBacks!=null){
                    callBacks.onError(e.getMessage());
                }
            }

            @Override
            public void onNext(ResponseBody o) {
                if(callBacks!=null){
                    try {
                        callBacks.onSuccess(o.string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        myApiService.upLoadImage(url,map,file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }


    public interface CallBacks{
        void onSuccess(String jsonStr);
        void onError(String jsonStr);
    }
}

4、MVC

**M**
//接口
void postImage(String url, Class cla, Map map, MultipartBody.Part file, MyCallBack myCallBack);
//类
@Override
public void postImage(String url, final Class cla, Map map, MultipartBody.Part file, final MyCallBack myCallBack) {
   RetrofitUtils.getInstance().upLoadImage(url, map, file, new RetrofitUtils.CallBacks() {
       @Override
       public void onSuccess(String jsonStr) {
           Gson gson = new Gson();
           Object o = gson.fromJson(jsonStr, cla);
           myCallBack.setSuccess(o);
       }

       @Override
       public void onError(String jsonStr) {

       }
   });
}

**P**
//接口
void postImage(String url, Class cla, Map map, MultipartBody.Part file);
//类
@Override
public void postImage(String url, Class cla, Map map, MultipartBody.Part file) {
   myModel.postImage(url, cla, map, file, new MyCallBack() {
       @Override
       public void setSuccess(Object successData) {
           iView.success(successData);
       }

       @Override
       public void setError(Object errorData) {
           iView.error(errorData);
       }
   });
}

5、Activity(Fragment)

//点击拍照
@OnClick(R.id.icon)
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.icon:
            icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    View view = View.inflate(getActivity(), R.layout.pop, null);
                    pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                    pop.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                    pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                    TextView paizhao = (TextView) view.findViewById(R.id.paizhao);
                    TextView xiangce = (TextView) view.findViewById(R.id.xiangce);
                    TextView cancel = (TextView) view.findViewById(R.id.cancel);
                    //拍照
                    paizhao.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/bai.png"));
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                            startActivityForResult(intent,1000);
                        }
                    });
                    //相册
                    xiangce.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            startActivityForResult(intent, 2000);
                        }
                    });
                    //取消
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pop.dismiss();
                        }
                    });
                }
            });
            break;
    }
}

//成功回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1000&&resultCode==getActivity().RESULT_OK) {
        crop(mUri);
    }
    if (requestCode == 2000 && resultCode==getActivity().RESULT_OK) {
        Uri uri = data.getData();
        crop(uri);
        pop.dismiss();
    }
    if (requestCode == 3000 && resultCode==getActivity().RESULT_OK) {
        Bitmap bitmap = data.getParcelableExtra("data");
        String crop = saveImage("crop", bitmap);
        Map partMap=new HashMap<>();
        MultipartBody.Part body = null;
        if(crop!=null){
            File file=new File(crop);
            if(file.exists()) {
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
                body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            }
        }
        Map map2=new HashMap<>();
        map2.put("uid",""+23830);
        myPresenter.postImage(Contrats.UPLOAD,UploadBean.class,map2,body);
        icon.setImageBitmap(bitmap);
    }
}

//裁剪
private void crop(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    //裁减比例1:1
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    //裁剪后图片大小
    intent.putExtra("outputX", 250);
    intent.putExtra("outputY", 250);
    intent.putExtra("outputFormat", "JPEG");
    intent.putExtra("noFaceDatection", false);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 3000);
}


//保存图片
private String saveImage(String crop, Bitmap bitmap) {
    File appDir = new File(Environment.getExternalStorageDirectory().getPath());
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = crop + ".png";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
        return file.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

你可能感兴趣的:(简单的Retrofit上传头像)