从 Uri 类型 android 创建文件

2024-03-12

我正在尝试从图库中选择图像,然后将此图像转换为文件并通过 HttpPost 发送,但我总是FileNotFoundException。这是我的代码:

选择照片

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                // currImageURI is the global variable I’m using to hold the content:
                currImageURI = data.getData();
                //Save the currImageUri (URI type) to global variable.
                photosHolder.getInstance().setOneIm(currImageURI);
            }
        }
    }

转换照片

                // First Try
                File myFile = new File((photosHolder.getInstance().getOneIm()).toString());
                params.put("visit_report[photos_attributes][0][file]",myFile); **The exception Raised here
// second try 
                File myFile2 = new File((photosHolder.getInstance().getOneIm()).getPath());
                params.put("visit_report[photos_attributes][1][file]",myFile2); ** Also here

这些是我在调试时的文件值:

mFile : content:/com.android.providers.media.documents/document/image%3A19143
myFile2 : /document/image:19143

那么有什么帮助吗?


Update我也尝试过这个解决方案:

//get The real path from uri then save it (and then use it to create the file)
photosHolder.getInstance().setUriString(getRealPathFromURI(currImageURI));

//Convert the image URI to the direct file system path of the image file
    private String getRealPathFromURI(Uri contentURI) {
        String result = "";
        try {
        Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            result = cursor.getString(idx); // Exception raised HERE
            cursor.close(); }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

但我得到了java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from itidx变量==到-1

我也尝试过@Praneeth Kalluri 解决方案,但它始终返回 null 作为结果。


 Uri currImageURI = data.getData();

打印 currImageURI 会给你这样的东西:

content://media/external/images/media/47

但我们需要的是该特定图像的绝对路径。所以我们需要从uri中获取真实的路径

public 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();
    }
  }
}

现在修改您的代码,例如

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                // currImageURI is the global variable I’m using to hold the content:
                currImageURI = data.getData();
                //Save the currImageUri (URI type) to global variable.
                photosHolder.getInstance().setOneIm(getRealPathFromURI(getActivity(),currImageURI));
            }
        }
    }

public 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();
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Uri 类型 android 创建文件 的相关文章

随机推荐

  • 如何在 jQuery Mobile 中检测设备的互联网连接

    我正在使用 HTML5 CSS3 jQuery Mobile jQuery UI ASP NET C 和一些 jQuery 插件为调查创建这个简单的移动网页 要求之一是显示一个弹出窗口 对话框 JavaScript 警报或 jQuery 移
  • 使用 Saxon 读取 XSLT 样式表中的环境变量

    我正在尝试生成一个 XML 文件 其中包含我的机器的主机名的任意元素或属性 例如
  • 通用类的通用父级

    我为此使用了一个虚构的例子 比如说 我有一个 Widget 类 例如 abstract class Widget Widget parent 现在 我的其他类将从这个 Widget 类派生 但假设我想在定义派生类型时在类中放置一些约束 以便
  • 如何在android上使用kso​​ap2调用WCF服务?

    这是我的代码 import org ksoap2 import org ksoap2 serialization import org ksoap2 transport import android app Activity import
  • 无法在PHP中的遍历预序中显示所有树

    我的数据库中有一个表 其中包含许多家谱树 id name parent id 1 grandfather NULL 2 father 1 3 uncle 1 4 son 2 5 brother 2 6 cousin s dauther 7
  • R 中随机森林的分层抽样

    我在文档中阅读了以下内容randomForest strata 用于分层抽样的 因子 变量 sampsize 要绘制的样本大小 对于分类 如果 sampsize 是一个长度为层数的向量 然后采样 按strata分层 sampsize的元素
  • 装饰器可以装饰递归函数吗?

    我想看看两种计算斐波那契数列的方法之间的时间成本差异 首先 我创建了一个装饰器 将 输出时间成本 函数添加到函数中 def time cost func def wed n start time time func n stop time
  • SQL依赖+服务代理

    我正在使用 SqlDependency 在某些表中的数据发生更改时获取通知 private void subscribeBroker using var conn new SqlConnection connString conn Open
  • 在Python中使用curses和raw_input

    在我的Python Linux控制台应用程序中 我使用curses来处理数据的显示 同时 我希望有一个输入行来输入命令 几乎是良好的 ol irssi 风格 使用默认的curses getch 我必须做大量的编码才能获得raw input函
  • 如何使 clang-format 尊重“类似表格”的代码格式

    我的代码具有按列对齐的数据或参数表 如下所示 人为的简单示例 实际代码具有更大的表 Name Size Starting val S s Dubs abc 123 X n m YZ ij q kl Name Size Starting va
  • 建议的解决方案:在分布式环境中生成唯一 ID

    我一直在浏览网络 试图找到一种解决方案 使我们能够在区域分布式环境中生成唯一的 ID 我查看了以下选项 除其他外 雪花 推特 这似乎是一个很棒的解决方案 但我只是不喜欢仅仅为了创建 ID 而必须管理另一个软件所带来的额外复杂性 现阶段缺乏文
  • Microsoft Word 中的 docx“文件已损坏”错误

    我写了一个程序 它打开docx包并更改一些
  • 使用 Java 与 MySQL 服务器的 SSL 连接

    我正在尝试使用 Java over SSL 连接到 MySQL 服务器 我收到以下异常 com mysql jdbc exceptions jdbc4 MySQLNonTransientConnectionException Cannot
  • Docker compose 和外部镜像多阶段构建

    I use Docker 多阶段构建 https docs docker com develop develop images multistage build 具体来说 使用外部图像作为 舞台 当使用多阶段构建时 您 不限于从您之前创建的
  • CLion C++ 无法读取/打开项目目录中的 .txt 文件

    我的项目目录中有一个我创建并填充了数据的 txt 文件 目录结构如下 Users asd ClionProjects ProjectWithTemplates main cpp cmake twoday txt 这是我的代码 include
  • 强制 UIImageView 的 CABasicAnimation 顺时针/逆时针旋转

    我正在制作一个钟摆的动画 该钟摆从 0 度摆动到最大 200 度 然后再返回 问题是 如果摆超过 180 度 它会通过最短路线返回到 0 度 即继续顺时针旋转 我希望它逆时针旋转 这是我的代码 right 是一个布尔值 当钟摆从左向右摆动时
  • 数据库查询生成器 toArray() laravel 4

    我正在尝试使用该方法将查询转换为数组toArray 但它不适用于查询生成器 有什么转换的想法吗 Example DB table user gt where name Jhon gt get gt toArray 如果您更喜欢使用查询生成器
  • 使用 R/ggplot2 损坏的条形图[重复]

    这个问题在这里已经有答案了 当存在一些极端计数时 我在缩放条形图时遇到困难 当它上升得更高时 很难看到较低的计数并在绘图上比较它们 我想打破条形图以重新调整它的比例 我知道重新调整比例是不好的绘图 但我只想在需要时这样做 我在附加链接中找到
  • 当用户跳过其中一个edittext并在下一个edittext上输入数据时如何提示错误?

    在此我有八个edittext 如果用户在edittext1处输入输入 则会跳过edittext 2并在edittext 3中输入数据 我需要向用户提示错误 并且try块内的else部分不会被执行 在哪里我错了我该如何纠正这个逻辑错误 pac
  • 从 Uri 类型 android 创建文件

    我正在尝试从图库中选择图像 然后将此图像转换为文件并通过 HttpPost 发送 但我总是FileNotFoundException 这是我的代码 选择照片 public void onActivityResult int requestC