首页 > 解决方案 > 从传递到 onActivityResult() 的 Intent 获取视频路径时找不到文件异常

问题描述

我是 android 编程新手,需要帮助解决我在捕获视频文件并将其上传到服务器时遇到的这个问题。我的活动 1 从使用原生视频捕获开始 -

private void recordVideo(){
    Intent takeVideoIntent = new 
    Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
    Uri videoUri = intent.getData();
    mVideoView.setVideoURI(videoUri);
    Log.d("Getting video path ", videoUri.getPath() );
  }
}

我通过将意图传递给活动 2 来上传到服务器。但是,在将文件上传到服务器时,我的应用程序崩溃了,因为我的 File 对象无法获取文件路径。我正在记录的文件路径示例是 - /external/video/media/18518。我没有使用任何外部存储,当我浏览我正在使用文件浏览器测试的 Lenovo K4 note 时,该文件不存在于

/外部/视频/媒体目录。相反,视频被存储在

"/内部存储/DCIM/Camera/test.mp4"

作为一种解决方法,我在我的活动 2 代码中硬编码了这个文件路径,它正在读取文件并将其上传到服务器,但仍然得到文件未找到异常 -

            int readedBytes;
            byte[] buf = new byte[1024];
            File file = new File("/Internal Storage/DCIM/Camera/test.mp4");
            InputStream insputStream = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            long length = file.length();
            byte[] bytes = new byte[(int) length];
            insputStream.read(bytes);
            while((readedBytes = insputStream.read(buf)) >0 ){
                bos.write(buf, 0, readedBytes);
            }
            insputStream.close();


java.io.FileNotFoundException: /Internal Storage/DCIM/Camera/test.mp4: open failed: ENOENT (No such file or directory)
05-04 00:06:14.432 23628-24496/com.example.jayant.healthapp W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:496)
05-04 00:06:14.433 23628-24496/com.example.jayant.healthapp W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)

这个问题的任何指针都会有很大的帮助。

标签: android

解决方案


但是,在将文件上传到服务器时,我的应用程序崩溃了,因为我的 File 对象无法获取文件路径。

你没有得到一个文件。你得到一个Uri. AUri不是文件。特别是Uri,你得到的有一个content方案,它可以指向相机应用程序希望它指向的任何东西。

使用ContentResolveropenInputStream()来获取InputStreamUri.

我在我的活动 2 代码中硬编码了这个文件路径

这不是任何 Android 设备上的有效文件路径。

相反,视频被存储在“/Internal Storage/DCIM/Camera/test.mp4”中

不它不是。您似乎混淆了某些文件管理器可能报告的内容与 Android 设备本身实际使用的内容。

用于Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)获取设备自己的文件系统路径,该路径应映射到DCIM/您所看到的目录。


推荐阅读