点击头像上传头像

//封装的工具类
HttpUtils

package com.bwie.zhuyue.sctxlianxi.net;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class HttpUtils {

private String baseUrl="http://172.17.8.100";
private Map headMap;
public HttpUtils setHead(Map headMap){
    this.headMap=headMap;
    return this;
}

  public HttpUtils upload(String url,File file){
      final MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
      RequestBody body=RequestBody.create(mediaType,file);
      MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(),body);

      HttpService httpService = getHttpService();
      httpService.uploadPic(url,headMap,part)
              .observeOn(AndroidSchedulers.mainThread())
              .subscribeOn(Schedulers.io())
              .subscribe(new Observer() {
                  @Override
                  public void onSubscribe(Disposable d) {

                  }

                  @Override
                  public void onNext(ResponseBody responseBody) {
                      try {
                       if (mHttpListener!=null) {
                           mHttpListener.success(responseBody.string());
                       }
                       if (mHttpStreamListener!=null){
                           mHttpStreamListener.success(responseBody.byteStream());
                       }
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }

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

                  @Override
                  public void onComplete() {

                  }
              });

      return this;
}

private HttpService getHttpService(){
Retrofit retrofit=new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(baseUrl)
.build();
HttpService httpService = retrofit.create(HttpService.class);
return httpService;
}

private HttpListener mHttpListener;
public void result(HttpListener mHttpListener){
this.mHttpListener=mHttpListener;
}

public interface HttpListener{
    void success(String data);
    void failed(String error);
}

private HttpStreamListener mHttpStreamListener;

public void setmHttpStreamListener(HttpStreamListener mHttpStreamListener) {
    this.mHttpStreamListener = mHttpStreamListener;
}

public interface HttpStreamListener{
  void success(InputStream inputStream);
  void failed(String error);

}

}
//HttpService
package com.bwie.zhuyue.sctxlianxi.net;

import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.HeaderMap;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Url;

public interface HttpService {

//上传
@Multipart
@POST
Observable uploadPic(@Url String url,
                             @HeaderMap Map headmap,
                             @Part MultipartBody.Part part);

}

//popuWin的xml















//MaActivity

package com.bwie.zhuyue.sctxlianxi;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.zhuyue.sctxlianxi.net.HttpUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.RowId;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
@BindView(R.id.image)
ImageView image;
private PopupWindow window;
private static String path = “/sdcard/head.jpg”;//sd路径

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuwin, null);
            window = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            window.setContentView(view);
            window.setOutsideTouchable(true);
            TextView xj = view.findViewById(R.id.xj);
            TextView xc = view.findViewById(R.id.xc);
            TextView qx = view.findViewById(R.id.qx);
            xj.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "head.jpg")));
                    startActivityForResult(intent2, 2);//采用ForResult打开
                    window.dismiss();
                }
            });
            xc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 1);
                    window.dismiss();
                }
            });
            qx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                }
            });
            View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
            window.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);

        }


    });
}

/**
 * 调用系统的裁剪
 *
 * @param uri
 */
public void cropPhoto(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    // aspectX aspectY 是宽高的比例
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    // outputX outputY 是裁剪图片宽高
    intent.putExtra("outputX", 127);
    intent.putExtra("outputY", 127);
    intent.putExtra("scale", true);
    intent.putExtra("noFaceDetection", false);//不启用人脸识别
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 3);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                cropPhoto(data.getData());//裁剪图片
            }
            break;
        case 2:
            if (resultCode == RESULT_OK) {
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/head.jpg";
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/head.jpg");
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                image.setImageBitmap(bitmap);
                cropPhoto(Uri.fromFile(temp));//裁剪图片
                upLoad(new File(path));
            }
            break;
        case 3:
            if (data != null) {
                Bundle extras = data.getExtras();
                if (extras == null) {
                    return;
                }
                Bitmap head = extras.getParcelable("data");
                image.setImageBitmap(head);
                setPicToView(head);
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/head.jpg";
                upLoad(new File(path));
            }


            break;
    }

}


//上传
private String upUrl = "/small/user/verify/v1/modifyHeadPic";//上传

private void upLoad(File file) {
    Map headMap = new HashMap<>();
    headMap.put("userId", "2128");
    headMap.put("sessionId", "15566131037482128");
    new HttpUtils().setHead(headMap).upload(upUrl, file).result(new HttpUtils.HttpListener() {
        @Override
        public void success(String data) {
            Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
        }

        @Override
        public void failed(String error) {
            Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show();
        }
    });


}

//保存到SD卡
private void setPicToView(Bitmap mBitmap) {
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/head.jpg");

    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);// 把数据写入文件
        //关闭流
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();

    }
}

}

你可能感兴趣的:(点击头像上传头像)