我已经将图像发送到Web服务器,所以我没有使用base64方法我已经将图像文件路径发送到Web服务器 . 我的要求是图库中的图像选择和图像从图像发送到网络服务器的摄像头 . 这些功能是精细的三星设备到棉花糖其他模型设备不适合低端和高端, Pick images from gallery its working all model device (low end to high end) 这是我的代码,请指导我 .

我的onActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == CAMERA_REQUEST) {

                if(data!=null) {

                    Bitmap photo = (Bitmap) data.getExtras().get("data");
                    //imageView.setImageBitmap(photo);
                    txt_complaint_name.setText(complientResponse.getD().get(position).getComplaintCatogoryName());
                    String encodedImage = encodeImage(photo);

                    //final Uri selectedFileUri = Uri.parse(encodedImage);

                    final Uri selectedFileUri = data.getData();
                    selectedFilePath = FilePath.getPath(this,selectedFileUri);
                    Log.i(TAG,"Selected File Path:" + selectedFilePath);

                    if(selectedFilePath != null && !selectedFilePath.equals("")){
    //                        tvFileName.setText(selectedFilePath);
                    }else{
                        Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
                    }


                    //on upload button Click
                    if(selectedFilePath != null){
    //                    dialog = ProgressDialog.show(ComplaintDetailsActivity.this,"","Uploading File...",true);

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //creating new thread to handle Http Operations
    //                            uploadFile(selectedFilePath);
                                uploadFiles(selectedFilePath, selectedFileUri);

                            }
                        }).start();
                    }else{
                        Toast.makeText(ComplaintDetailsActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
                    }


                    Log.d("base64", encodedImage);

                    BitmapFactory.Options options;
                    options = new BitmapFactory.Options();
                    options.inSampleSize = 5;

                    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();

                    if (photo != null) {
                        photo.compress(Bitmap.CompressFormat.JPEG, 10, baos1);
                        byte[] b1 = baos1.toByteArray();

                        String bitmapstring1 = Base64.encodeToString(b1,
                                Base64.NO_WRAP);

                        Log.d("full_string", bitmapstring1);
                        String imageBase64 = bitmapstring1;
                        ComplaintDetailsActivity obj = new ComplaintDetailsActivity();
                        obj.imageVal(bitmapstring1);

                        f = new File(Environment.getExternalStorageDirectory().toString());
                        for (File temp : f.listFiles()) {
                            if (temp.getName().equals("temp.jpg")) {
                                f = temp;
                                break;
                            }
                        }
                        imageuri = f.getAbsolutePath();

                        questionResponse.getD().get(adapterPosition).setImage(imageBase64);
                        adapterQuestionMaster.notifyDataSetChanged();



                    }
                }
            }
            else if (requestCode == GALLERY_REQUEST) {

                super.onActivityResult(requestCode, resultCode, data);
                if(resultCode == Activity.RESULT_OK){

                    if(requestCode == PICK_FILE_REQUEST){
                        if(data == null){
                            //no data present
                            return;
                        }

    //                    Bitmap photo = (Bitmap) data.getExtras().get("data");
    //
    //                    String encodedImage = encodeImage(photo);
    //                    questionResponse.getD().get(adapterPosition).setImage(encodedImage);


                        final Uri selectedFileUri = data.getData();
                        selectedFilePath = FilePath.getPath(this,selectedFileUri);
                        Log.d("Path", selectedFilePath);
                        InputStream imageStream = null;
                        try {
                            imageStream = this.getContentResolver().openInputStream(selectedFileUri);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        Bitmap photo = BitmapFactory.decodeStream(imageStream);
                        try
                        {
    //                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver() , Uri.parse(selectedFilePath));
                            String encodedImage = encodeImage(photo);
                            Log.d("full_string", encodedImage);
                            Log.d("full_string", "SSSS");
                            BitmapFactory.Options options;
                            options = new BitmapFactory.Options();
                            options.inSampleSize = 5;

                            ByteArrayOutputStream baos1 = new ByteArrayOutputStream();

                            if (photo != null) {
                                photo.compress(Bitmap.CompressFormat.JPEG, 10, baos1);
                                byte[] b1 = baos1.toByteArray();

                                String bitmapstring1 = Base64.encodeToString(b1,
                                        Base64.NO_WRAP);

                                Log.d("full_string", bitmapstring1);
                                String imageBase64 = bitmapstring1;
                                ComplaintDetailsActivity obj = new ComplaintDetailsActivity();
                                obj.imageVal(bitmapstring1);

                                f = new File(Environment.getExternalStorageDirectory().toString());
                                for (File temp : f.listFiles()) {
                                    if (temp.getName().equals("temp.jpg")) {
                                        f = temp;
                                        break;
                                    }
                                }
                                imageuri = f.getAbsolutePath();

                                questionResponse.getD().get(adapterPosition).setImage(encodedImage);
                                adapterQuestionMaster.notifyDataSetChanged();
                            }
                        }
                        catch (Exception e)
                        {
                            //handle exception
                        }
                        Log.i(TAG,"Selected File Path:" + selectedFilePath);

                        if(selectedFilePath != null && !selectedFilePath.equals("")){
    //                        tvFileName.setText(selectedFilePath);
                        }else{
                            Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
                        }

                        //on upload button Click
                        if(selectedFilePath != null){
    //                        dialog = ProgressDialog.show(ComplaintDetailsActivity.this,"","Uploading File...",true);

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //creating new thread to handle Http Operations
    //                                uploadFile(selectedFilePath);
                                    uploadFiles(selectedFilePath, selectedFileUri);
                                }
                            }).start();
                        }else{
                            Toast.makeText(ComplaintDetailsActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

        }

我的FilePath:

public class FilePath {

    /**
     * Method for return file path of Gallery image/ Document / Video / Audio
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    //@RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        // check here to KITKAT or new version
        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 the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            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 index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(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());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }
}

uploadFile类:

private void uploadFiles(final String selectedFilePath,final Uri fileUri) {


        //creating a file
        File file = new File(selectedFilePath);

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);


        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        //creating our api

        userService = RetrofitClient.getApiServiceFile();

        //creating a call and calling the upload image method
        Call<ImageResponse> call = userService.uploadImage(requestFile);

        //finally performing the call
        call.enqueue(new Callback<ImageResponse>() {
            @Override
            public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {

             //   dialog.dismiss();
                ImageResponse imageResponse = response.body();

//                questionResponse.getD().get(adapterPosition).setImage(imageResponse.getImageName());
                    Log.d("response32",imageResponse.getImageName());
                    ImageName =imageResponse.getImageName();
                ImageId = imageResponse.getImageID();
                questionResponse.getD().get(adapterPosition).setImageName(ImageName);
                questionResponse.getD().get(adapterPosition).setImageID(ImageId);
                adapterQuestionMaster.notifyDataSetChanged();
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();

            }

            @Override
            public void onFailure(Call<ImageResponse> call, Throwable t) {
//                dialog.dismiss();
            }
        });
    }

这是我的错误:

E / AndroidRuntime:FATAL EXCEPTION:main进程:com.example.ggs.tvscomplaintstudy,PID:18656 java.lang.RuntimeException:传递结果失败ResultInfo {who = null,request = 1,result = -1,data = Intent { act = inline-data(has extras)}} to activity {com.example.ggs.tvscomplaintstudy / com.example.ggs.tvscomplaintstudy.app.complaint_details.ComplaintDetailsActivity}:java.lang.NullPointerException:尝试调用虚方法'java .lang.String android.net.Uri.getScheme()'在Android.app.ActivityThread.handleSendResult(ActivityThread.java:4975)的android.app.ActivityThread.deliverResults(ActivityThread.java:4932)上的空对象引用android.app.ActivityThread.-wrap20(未知来源:0)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1950)android.os.Handler.dispatchMessage(Handler.java:108)android.os位于com.an的java.lang.reflect.Method.invoke(Native Method)的android.app.ActivityThread.main(ActivityThread.java:7425)上的.Looper.loop(Looper.java:166) droid.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:245)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)引起:java.lang.NullPointerException:尝试调用虚拟方法'java.lang.String android.net.Uri.getScheme()'在com.example的com.example.ggs.tvscomplaintstudy.app.complaint_details.FilePath.getPath(FilePath.java:79)上的空对象引用上 . 在Android.app.ActivityThread.deliverResults(ActivityThread.java:4928)的android.app.Activity.dispatchActivityResult(Activity.java:7690)上的ggs.tvscomplaintstudy.app.complaint_details.ComplaintDetailsActivity.onActivityResult(ComplaintDetailsActivity.java:1118) .app.ActivityThread.handleSendResult(ActivityThread.java:4975)在android.app上的android.app.ActivityThread.-wrap20(未知来源:0)android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1950) . Handler.dispatchMessage(Handler.java:108)位于android.app.ActivityThread.main(ActivityThread.j)的android.os.Looper.loop(Looper.java:166) ava:7425)位于com.android.internal.os.ZygoteInit的com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:245)的java.lang.reflect.Method.invoke(Native Method) . 主(ZygoteInit.java:921)