android - 使用棉花糖设备从 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);
}
解决方案
您是否检查了清单文件的权限?我之前遇到过类似的问题,因为我没有写这些。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
并使用 PackageManager 检查是否授予了所需的权限。
推荐阅读
- c# - WPF条形图如何在条形之间添加空间?
- windows - 如何创建任务以定期检查另一个计划任务并在存在时将其删除?
- firebase - Cloud Firestore 中是否有可能出现慢查询?
- c# - 如何获取系统的 MAC ID
- reactjs - React-Navigation 在 tabNavigation 上显示动态标题
- javascript - 在 Mapbox 中根据地理位置记录行驶路线
- powershell - 启用 IISNET45 时出错
- python - 如何将数据集中存在的单个数据训练到已经训练好的神经网络?
- javascript - 具有多个子域的 Javascript window.opener.postMessage 跨域
- jquery - 在从 jquery 生成的列表中换行