Cordova 3.6.3 File plugin - get local video file o

2020-07-20 03:39发布

问题:

What I'd like to do is

  1. get the URI of a video file on the device via cordovas javascript API
  2. set the URI as value of a HTML5 video tag's src attribute.

The second part shouldn’t be a problem.
Concerning the first task, there are a lot of good structured tutorials like Raymond Camden's demonstrating how to get local files through javascript in an cordova environment.

However, with the newest version of cordova, I could not get it to work.

The video file

The video is located either in assets/www/videos/testvid.webm or res/raw/testvid.webm in the built apk file. Both variations did not work.

The javascript

myPath = cordova.file.applicationDirectory; // -> file:///android_asset/
//myPath += "www/videos/testvid.webm";

respectively

myPath = cordova.file.applicationStorageDirectory; // -> file:///data/data/com.example.MyPackage/
//myPath += "raw/testvid.webm";

Then:

window.resolveLocalFileSystemURL(myPath, gotFile, fail);
function gotFile(entry){
  if(entry.isDirectory)
    alert JSON.stringify(entry.getFile("testvid.webm"));
}

The permissions

In res/xml/config.xml access permissions are added

<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />

The error is {code:1} -> NOT_FOUND_ERR

What am I doing wrong? How to navigate to the file, or where can one put it to be found?

回答1:

I figured it out!

There is a bug in the android version of the cordova file plugin.

A workaround is transferring the file(s) from the assets directory of the app itself file:///android_asset/ (cordova.file.applicationDirectory) to a working directory on the phone like file:///data/data/com.example.MyPackage/files (cordova.file.dataDirectory). Then set the video's source URL to this new file.

XMLHttpRequest as well as FileTransfer will do the trick.

var myFilename = "testvid.webm";
var myUrl = cordova.file.applicationDirectory + "www/videos/" + myFilename;
var fileTransfer = new FileTransfer();
var filePath = cordova.file.dataDirectory + myFilename;

fileTransfer.download(encodeURI(myUrl), filePath, (function(entry) {
  /*
  res = "download complete:\n"
  res += "fullPath: " + entry.fullPath + "\n"
  res += "localURL: " + entry.localURL + "\n"
  alert(res += "nativeURL: " + entry.nativeURL + "\n")
   */
  var vid = document.getElementById("someID");
  vid.src = entry.nativeURL;
  vid.loop = true;
}), (function(error) {
  alert("Video download error: source " + error.source);
  alert("Video download error: target " + error.target);
}), true, {
  headers: {
    Authorization: "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
  }
});