2017-05-03 125 views
2

我在挑选文件的文件路径时遇到了问题,我搜索了所有堆栈溢出,但问题没有解决。从设备中选择文件的代码如下所示。如何从android中的外部存储获取文件路径?

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
      intent.setType("*/*"); 
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
      //intent.addFlags(ST) 
      startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST); 

从意图拾取文件由

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == Activity.RESULT_OK) { 
     if (requestCode == PICK_FILE_REQUEST) { 
      if (data != null) { 
       //no data present 
       Uri uri = data.getData(); 
       String filePath = data.getData().getPath(); 
     //  String path = uri.getPath(); 
       file = new File(filePath); 

       String name = getContentName(getContentResolver(), uri); 
       try { 
        InputStream inStream = getContentResolver().openInputStream(uri); 

       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
       try { 
        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); 

       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       LinearLayout linearLayout = new LinearLayout(this); 
       linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
         LinearLayout.LayoutParams.WRAP_CONTENT)); 
       linearLayout.setOrientation(LinearLayout.VERTICAL); 

       ImageView imageView = new ImageView(this); 
       imageView.setImageBitmap(bitmap); 
       attachFile.addView(imageView); 


       TextView textView = new TextView(this); 
       textView.setText(name); 
       attachFile.addView(textView); 

       return; 
      } 

     } 
    } 

}

在上面的代码文件路径获得由`字符串文件路径= data.getData()获得的。的getPath() ;但是当上传文件到服务器异常被抛出像无效的文件和文件。如何从uri获取文件的正确路径?

但文件的名称是通过使用

`public static String getContentName(ContentResolver resolver, Uri uri) { 
     Cursor cursor = resolver.query(uri, null, null, null, null); 
     cursor.moveToFirst(); 
     int nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME); 
     if (nameIndex >= 0) { 
      return cursor.getString(nameIndex); 
     } else { 
      return null; 
     } 
    }` 

如何获得拾取文件正确的文件路径挑?

回答

1

如何获取拾取文件的正确文件路径?

你不知道。没有文件。 ACTION_GET_CONTENT与文件无关。它与内容有关。

使用ContentResolveropenInputStream()Uri标识的内容一起使用。对于上传,或者:

  • 给这个InputStream到上传API,如果它可以从上传,或

  • 使用InputStreamFileOutputStream一些你控制文件(例如,在getCacheDir() )复制内容,然后从本地副本上传

相关问题