Cordova: Getting a file Uri from a content Uri

2019-05-22 16:27发布

问题:

I implemented an app with Apache Cordova and I used $cordovaCamera plugin. When the source type of $cordovaCamera is Camera.PictureSourceType.PHOTOLIBRARY the output is something like

"content://com.android.providers.media.documents/document/image"

and, when I use Camera.PictureSourceType.CAMERA I get

"file:///storage/emulated/0/Android/data/com.ionic.viewapp/cache/image.jpg".

In my case the format "file://.." is more useful.

It is possible get the file URI from the content URI?

I found many answers to this questions but all solutions are for JAVA, not for Javascript.

回答1:

I found the problem. I'm using Ionic and Ionic View for test in device.

When I tried the cordova-plugin-filepath it didn't work. But I found that the problem was that in Ionic View this plugin fails.

So, I wrote in a service this function:

// data is the return of $cordovaCamera.getPicture.

    getFilePath: function(data){ 
             var deferred = $q.defer();
             window.FilePath.resolveNativePath(data, function(result) {
                    deferred.resolve('file://' + result;);
                  }, function (error) {
                      throw new Error("");
                  });

             return deferred.promise;
         }

to return the file URI that I needed it. Then, I installed the apk in the phone, and it works. Now, I can store an image obtained from the camera or gallery and upload to the server.



回答2:

There is an error in answer above.

After window.FilePath.resolveNativePath succeed, its result already has format: file:///..., so no need to prepend file://.