首页 > 解决方案 > 使用棉花糖设备从 SD 卡上传 pdf 文件在 Android 应用程序中不起作用。但从手机内存中工作正常

问题描述

我已将 PDF 文件上传到服务器,但无法从 Marshmallow 中的 sd 卡获取路径。有人可以帮忙找出问题所在吗?

but_browse是浏览文件的按钮,浏览后我给出了一个上传按钮,可以将 PDF 上传到服务器。

but_browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //sets the select file to all types of files

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("application/pdf");
                //intent.putExtra("browseCoa", itemToBrowse);
                //Intent chooser = Intent.createChooser(intent, "Select a File to Upload");
                try {
                    //startActivityForResult(chooser, FILE_SELECT_CODE);
                    startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 1);
                } catch (Exception ex) {
                    System.out.println("browseClick :" + ex);//android.content.ActivityNotFoundException ex
                }   
            }
        });

onActivityResult()方法:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        // if (requestCode == 1) {
        Uri uri = data.getData();

        String uriString = uri.toString();

        // uploadedFileName = file.getName().toString();
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {   
            File myFile = new File(uriString);
            // selectedFilePath2 = PathUtils.getPath(getActivity(), uri );

            System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2"+ getApplicationContext().getFilesDir().getPath());
            // System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
            // file_name = file.getName();
            // Log.i("", "File : " + file.getName());

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                File[] externalCacheDirs = getActivity().getExternalCacheDirs();
                String[] f = getExternalStorageDirectories();
                System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath3" + f );
                for (File file : externalCacheDirs) {
                    if (Environment.isExternalStorageRemovable(file)) {
                        // Path is in format /storage.../Android....
                        // Get everything before /Android
                        selectedFilePath2 = file.getPath().split("/Android")[0];
                            System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2 );

                        break;
                    }
                }

                selectedFilePath2 = myFile.getAbsolutePath();

                System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2 );

            }
        }

        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {    

            File myFile = new File(uriString);
            selectedFilePath2 = PathUtils.getPath(getActivity(), uri );

            System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2);
            System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2"+ getApplicationContext().getFilesDir().getPath());
           // System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
           // file_name=  file.getName();
           // Log.i("", "File : " + file.getName());   
        } else {
            file = new File(uri.getPath().toString());
            selectedFilePath2 = Vis_FilePath.getPath(getActivity(), uri) ;
            System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
            file_name=  file.getName();
            Log.i("", "File : " + file.getName());
        }
    }
}

上传到服务器:

private void uploadpdf() throws IOException {
    String charset = "UTF-8";    
    byte[] data = null;
    File filessss = new File(selectedFilePath2);

    try {    
        data = FileUtils.readFileToByteArray(filessss);
        pdf =  Base64.encodeToString(data, Base64.DEFAULT);
    } catch (IOException e) {    
        e.printStackTrace();
    }

    final ProgressDialog loading = ProgressDialog.show(getActivity(),"Uploading...","Please wait...",false,false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_CV,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(getActivity(), s , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(getActivity(), volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }){

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String

                //Creating parameters
                Map<String,String> params = new Hashtable<String, String>();
                SharedPreferences   prefs = getActivity().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                String userid = prefs.getString("userId","");

                //Adding parameters
                params.put("user_id",userid);
                params.put("attachment",pdf);

                //returning parameters
                return params;
            }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

标签: androidandroid-volley

解决方案


您是否检查了清单文件的权限?我之前遇到过类似的问题,因为我没有写这些。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

并使用 PackageManager 检查是否授予了所需的权限。

我从这里得到一些帮助:https ://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal


推荐阅读