安卓Android 图片URi转File,上传到服务器接口

1、打开图库拿到图片

//打开图库
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 0);

3、获取图片的路径

    //获取路径
        case 0:
            try {
                if (data != null) {
                    if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
                        //获取图片的URI地址
                        Uri selectedImage = data.getData();
                        //调用URL转file方法
                        File file = uri2File(selectedImage);
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String picPath = cursor.getString(columnIndex);
                        //转码
                        String encode = URLEncoder.encode(picPath, "utf-8");
                        cursor.close();
                        if (picPath.equals("")) return;
                        Log.e("123", "onActivityResult: 路径:--" + encode);
                        //上传图片
                        addimg(encode, file);
                        break;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

4、post请求上传到接口

/**
 * 上传到接口
 * retrofit
 * @Post
 *    Observable onepic(@Url String url, @Header("sessionId") String sessionId, @Header("userId") String userId, @Part MultipartBody.Part file);

 * @param picPath
 * @param file
 */
private void addimg(String picPath, File file) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.e("123", "图片文件路径: " +picPath );
        //创建文件请求对象
        //设置content-type类型
        RequestBody responseBody = RequestBody.create(MediaType.parse("image/*"), file);//file为文件
        //多表单上传的工具类
        MultipartBody.Part image = MultipartBody.Part.createFormData("image", picPath, responseBody);
        HttpUntil.getUntil().getService(UserApiService.class).onepic(url, sessionId, userId, image)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        Log.e("123", "上传图片成功: " + responseBody.string());
                    }
                }, new Consumer() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e("123", "上传图片失败-: " + throwable);
                    }
                });
    }
}

2、URL转file类型

/**
 * user转换为file文件
 *返回值为file类型
 * @param uri
 * @return
 */
private File uri2File(Uri uri) {
    String img_path;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null,
            null, null);
    if (actualimagecursor == null) {
        img_path = uri.getPath();
    } else {
        int actual_image_column_index = actualimagecursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        img_path = actualimagecursor
                .getString(actual_image_column_index);
    }
    File file = new File(img_path);
    return file;
}

你可能感兴趣的:(安卓)