OkHttp简易上传头像

Activity

 private ImageView img_pic;
    private PopupWindow mPopupWindow;
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;
    private static final String IMAGE_FILE_NAME = "header.jpg";
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img_pic = findViewById(R.id.img_pic);
        //点击图片的监听
        img_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //popwindow显示
                showPopWindow();
            }
        });
    }

    private void showPopWindow() {
        //加载popWindow
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow, null);
        //设置填充
        mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setContentView(view);
        //查找控件
        TextView text_xiang = view.findViewById(R.id.text_xiang);
        TextView text_phono = view.findViewById(R.id.text_phono);
        TextView text_quxiao = view.findViewById(R.id.text_quxiao);
        //按钮设置监听
        text_xiang.setOnClickListener(this);
        text_phono.setOnClickListener(this);
        text_quxiao.setOnClickListener(this);
        //显示popupWindow位置
        mPopupWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //拍照
            case R.id.text_xiang:
                //判断SD卡是否存在
                if(isSdcardExisting()){
                    //激活相机
                    Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
                    //获取图片路径getImageUri   将拍摄的图片存在我们想存的地方
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                    //MediaStore.EXTRA_VIDEO_QUALITY- 此值在最低质量最小文件尺寸时是0,在最高质量最大文件尺寸时是1.
                    cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                    // 开启一个带有返回值的Activity,请求码为CAMERA_REQUEST_CODE
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                } else {
                    //吐司不存在SD卡
                    Toast.makeText(v.getContext(), "请插入sd卡", Toast.LENGTH_LONG) .show();
                }
                //popWindows取消
                mPopupWindow.dismiss();
                break;
            case R.id.text_phono:
                //ACTION_PICK 选择数据
                Intent intent1 = new Intent(Intent.ACTION_PICK);
                //设置图片类型
                intent1.setType("image/*");
                // 开启一个带有返回值的Activity,请求码为IMAGE_REQUEST_CODE
                startActivityForResult(intent1, IMAGE_REQUEST_CODE);
                mPopupWindow.dismiss();
                break;
            case R.id.text_quxiao:
                mPopupWindow.dismiss();
                break;
        }
    }

    //获取图片的URI
    private Uri getImageUri() {
        file = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        return Uri.fromFile(file);
    }

    //判断SD卡是否存在
    private boolean isSdcardExisting() {
        // 判断SD卡是否存在,并且是否具有读写权限
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            //存在
            return true;
        }else{
            //不存在
            return false;
        }
    }
    //该方法是用于放回相应结果的
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){//成功
            switch (requestCode) {//通过请求码进行不同的执行
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if(isSdcardExisting()){
                        resizeImage(getImageUri());
                    }else{
                        Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!",
                                Toast.LENGTH_LONG).show();
                    }
                    break;
                case RESIZE_REQUEST_CODE:
                    // 从剪切图片返回的数据
                    if (data != null) {
                        Bitmap bitmap = data.getParcelableExtra("data");
                        //获得图片
                        img_pic.setImageBitmap(bitmap);
                    }
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 展示头像
     * @param data
     */
    private void showResizeImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            img_pic.setImageDrawable(drawable);
            headUploding();
        }
    }
    /**
     * 对图片进行处理
     * @param uri
     */
    private void resizeImage(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", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }
    public void headUploding(){
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建RequestBody 封装file参数
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //创建RequestBody 设置类型等
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), fileBody).build();
        //创建Request
        Request request = new Request.Builder().url("http://www.zhaoapi.cn/file/upload?uid=14646").post(requestBody).build();
        //得到Call
        okhttp3.Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                Log.d("成功", "onResponse: 开心");
            }
        });
    }

Pop

 <Button
        android:id="@+id/text_xiang"
        android:text="拍照"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/text_phono"
        android:text="相册"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/text_quxiao"
        android:text="取消"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值