如何在 android 中转换为 'file:///storage/sdcard0/Pictures/X.jpg' 的 'content://media/external/images/media/Y

我想从我的 android 应用程序,将图像上载到 Google 驱动器

基于本教程

调试他们的示例项目的时候我看到典型的 fileUri =

file:///storage/sdcard0/Pictures/IMG_20131117_090231.jpg

我想在我的应用程序上载现有的照片。

像这样检索它的路径

     private void GetAnyImage()
       
{
           
File dir = new File(Environment.getExternalStorageDirectory()
           
.getAbsolutePath() + "/Pictures/Screenshots");
                             
// --> /storage/sdcard0/Pictures/Screenshots

           
Log.d("File path ", dir.getPath());
           
String dirPath=dir.getAbsolutePath();
           
if(dir.exists() && dir.isDirectory()) {
               
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent
.setType("image/*");
                startActivityForResult
(intent,REQUEST_ID);
           
}  
       
}

最终会到达这个典型的 fileUri =content://media/external/images/media/74275

然而当运行这行代码

  private void saveFileToDrive() {

   
//  progressDialog = ProgressDialog.show(this, "", "Loading...");

   
Thread t = new Thread(new Runnable() {
     
@Override
     
public void run() {
       
try {
         
// File's binary content
          java
.io.File fileContent = new java.io.File(fileUri.getPath());
         
FileContent mediaContent = new FileContent("image/jpeg", fileContent);

     
// File's metadata.
     
File body = new File();
      body
.setTitle(fileContent.getName());
      body
.setMimeType("image/jpeg");

     
File file = service.files().insert(body, mediaContent).execute();

出现错误:

java.io.FileNotFoundException: /external/images/media/74275: open failed: ENOENT (No such file or directory)

如何解决这问题?

如何转换 content://media/external/images/media/Y 到 file:///storage/sdcard0/Pictures/X.jpg 吗?

解决方法 1:

什么会喜欢这项工作对你来说吗?这不会是查询的内容冲突解决程序来存储的文件路径数据寻找该内容的条目

public static String getRealPathFromUri(Context context, Uri contentUri) {
   
Cursor cursor = null;
   
try {
       
String[] proj = { MediaStore.Images.Media.DATA };
        cursor
= context.getContentResolver().query(contentUri, proj, null, null, null);
       
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor
.moveToFirst();
       
return cursor.getString(column_index);
   
} finally {
       
if (cursor != null) {
            cursor
.close();
       
}
   
}
}

这最终会给你你可以构造从一个文件 uri 的绝对文件路径

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值