android选择并上传pdf

原文链接:https://cloud.tencent.com/developer/ask/sof/289269

感觉博主的代码,解决了我的需求问题,这里记录一下,从手机最近文件选取pdf和图片文件并上传到服务器,解决了选择的pdf路径转为本地文件路径的问题。

 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    //todo when permission is granted
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");
                    String[] mimetypes = {"image/*", "application/*"};
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
                    startActivityForResult(intent, REQ_PDF);
                } else {
                    //request for the permission
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }
            } else {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");
                String[] mimetypes = {"image/*", "application/*"};
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
                startActivityForResult(intent, REQ_PDF);
            }
        }
    });

   @SuppressLint({"SetTextI18n", "NewApi"})
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    InputStream inputStream = null;
    try {
        if (requestCode == REQ_PDF && resultCode == RESULT_OK && data != null) {

            path = data.getData();
            inputStream = this.getContentResolver().openInputStream(path);
            byte[] pdfInBytes = new byte[inputStream.available()];
            inputStream.read(pdfInBytes);
            // Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
            String encodedCode = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
            filePath = PathUtil.getPathFromUri(this, path);
            // filePath= FileUtils.getPath(this,path);
            if (filePath == null) {
                // Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
                SharedPrefMannager.showAlertDialog(InvoiceGenerationActivity.this, "Alert!", "Please select a file from internal storage", true);
            } else {

                file = new File(filePath);
                file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
            }
            tv_attachFile.setText("Change File");
            tv_fileLocation.setVisibility(View.VISIBLE);
            tv_fileLocation.setText(filePath);

            //Toast.makeText(getContext(), encodedCode, Toast.LENGTH_SHORT).show();
        }
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(InvoiceGenerationActivity.this, "Something went wrong " + e, Toast.LENGTH_SHORT).show();
    }
}




public class PathUtil 
 {
    private static Uri contentUri = null;
     
    @SuppressLint("NewApi")
    public static String getPathFromUri(final Context context, final Uri uri) {
        // check here to is it KITKAT or new version
        final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String selection = null;
        String[] selectionArgs = null;

        // DocumentProvider
        if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                final String type = split[0];
                String fullPath = getPathFromExtSD(split);

                if (fullPath != "") {
                    return fullPath;
                } else {
                    return null;
                }
                //return getPathFromExtSD(split);
               /* String fullPath =Environment.getExternalStorageState() + "/" + split[1];
                if (fullPath != "") {
                    return fullPath;
                } else {
                    return null;
                }*/
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    final String id;
                    Cursor cursor = null;
                    try {
                        cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            String fileName = cursor.getString(0);
                            String path = getExternalStorageDirectory().toString() + "/Download/" + fileName;
                            if (!TextUtils.isEmpty(path)) {
                                return path;
                            }
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();
                    }
                    id = DocumentsContract.getDocumentId(uri);
                    if (!TextUtils.isEmpty(id)) {
                        if (id.startsWith("raw:")) {
                            return id.replaceFirst("raw:", "");
                        }
                        String[] contentUriPrefixesToTry = new String[]{
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads",
                                "content://downloads/all_downloads"
                        };
                        for (String contentUriPrefix : contentUriPrefixesToTry) {
                            try {
                                final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));

                                return getDataColumn(context, contentUri, null, null);
                            } catch (NumberFormatException e) {
                                //In Android 8 and Android P the id is not a number

                                return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
                            }
                        }
                    }

                } else {
                    final String id = DocumentsContract.getDocumentId(uri);

                    if (id.startsWith("raw:")) {
                        return id.replaceFirst("raw:", "");
                    }
                    try {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                            contentUri = ContentUris.withAppendedId(
                                    Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); //public
                        }
                        if (contentUri != null) {
                            return getDataColumn(context, contentUri, null, null);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
                    }


                }
            }
            // 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; //MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                contentUri = MediaStore.Files.getContentUri("external");
            	}
                selection = "_id=?";
                selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);


            } else if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri, context);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {

            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }

            if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri, context);
            }
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
                return getMediaFilePathForN(uri, context);
            } else {
                return getDataColumn(context, uri, null, null);
            }
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    private static boolean fileExists(String filePath) {
        File file = new File(filePath);

        return file.exists();
    }

    private static String getPathFromExtSD(String[] pathData) {
        String type = pathData[0];
        String relativePath = "/" + pathData[1];
        String fullPath = "";

        if ("primary".equalsIgnoreCase(type)) {
            fullPath = getExternalStorageDirectory() + relativePath;
            if (fileExists(fullPath)) {
                return fullPath;
            }
        }

        fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
        if ((null == fullPath) || (fullPath.length() == 0)) {
            fullPath = System.getenv("SECONDARY_SDCARD_STORAGE");
            return fullPath;
        }
      /*  if (fileExists(fullPath)) {
            return fullPath;
        }*/

        fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
        if ((null == fullPath) || (fullPath.length() == 0)) {
            fullPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
            return fullPath;
        }
     /*   if (fileExists(fullPath)) {
            return fullPath;
        }*/

        return fullPath;
    }

    private static String getDriveFilePath(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            inputStream = context.getContentResolver().openInputStream(uri);
            outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                }
            }
        }
        return file.getPath();
    }

    private static String getMediaFilePathForN(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);

        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getFilesDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }


    private 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);
            }
        } catch (Exception e) {
            //   Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
        } finally {
            if (cursor != null)
                cursor.close();
        }

        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 中选取本地 PDF 文件并上传,可以使用以下步骤: 1. 添加文件读取权限到 AndroidManifest.xml 文件中: ``` <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` 2. 在 Activity 中添加一个按钮或者其他触发事件的控件,用于打开文件选择器: ``` private static final int REQUEST_CODE = 1; private void chooseFile() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("application/pdf"); startActivityForResult(intent, REQUEST_CODE); } ``` 3. 在 Activity 中实现 onActivityResult() 方法,获取用户选择的文件的 URI,并进行上传操作: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); if (uri != null) { try { InputStream inputStream = getContentResolver().openInputStream(uri); // 进行上传操作 } catch (FileNotFoundException e) { e.printStackTrace(); } } } } ``` 在以上代码中,首先定义了一个请求码 REQUEST_CODE,用于在 onActivityResult() 方法中判断返回的结果是否是我们发起的请求。在 chooseFile() 方法中,使用 Intent.ACTION_GET_CONTENT 打开文件选择器,并设置类型为 "application/pdf",这样只会显示 PDF 文件。在 onActivityResult() 方法中,获取用户选择的文件的 URI,并使用 getContentResolver().openInputStream(uri) 获取文件的输入流,可以使用该输入流进行上传操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值