Cordova文件插件readAsDataURL不返回文件数据

时间:2017-01-26 16:28:16

标签: ionic2 cordova-plugins

我正在尝试使用Cordova File插件的readAsDataURL函数来获取视频文件的base64版本,但没有成功。我的代码如下所示:



  recordVideo()
  {
    return new Promise(resolve =>
    {
      let options: CaptureVideoOptions = { limit: 1, duration: 2 };
      MediaCapture.captureVideo(options)
        .then(
          (data: MediaFile[]) => {

            console.log('Media: recordVideo: cordova.file.dataDirectory = ' + cordova.file.dataDirectory + ', path = ' + data[0].fullPath.substring(1));

            // Turn the video file into base64
            let base64File = File.readAsDataURL(cordova.file.dataDirectory, data[0].fullPath.substring(1));

            console.log('Media: recordVideo: got video with data = ' + JSON.stringify(data));

            console.log('Media: recordVideo: base64File = ' + JSON.stringify(base64File));

            resolve(data);
          },
          (err: CaptureError) => console.error('ERROR - Media: recordVideo: captureVideo error = ' + err)
        );
    });
  }




第一个console.log的输出显示传递给readAsDataURL的参数值:

Media: recordVideo: cordova.file.dataDirectory = file:///var/mobile/Containers/Data/Application/764345DC-A77D-43C2-9DF7-CDBE6A0DC372/Library/NoCloud/, path = private/var/mobile/Containers/Data/Application/764345DC-A77D-43C2-9DF7-CDBE6A0DC372/tmp/50713961066__4FD8AF8D-BD36-43A4-99CC-F328ADFD7E38.MOV

第二个console.log显示MediaCapture插件返回的数据:

Media: recordVideo: got video with data = [{"name":"50713961066__4FD8AF8D-BD36-43A4-99CC-F328ADFD7E38.MOV","localURL":"cdvfile://localhost/temporary/50713961066__4FD8AF8D-BD36-43A4-99CC-F328ADFD7E38.MOV","type":"video/quicktime","lastModified":null,"lastModifiedDate":1485446813000,"size":195589,"start":0,"end":0,"fullPath":"/private/var/mobile/Containers/Data/Application/764345DC-A77D-43C2-9DF7-CDBE6A0DC372/tmp/50713961066__4FD8AF8D-BD36-43A4-99CC-F328ADFD7E38.MOV"}]

最后console.log显示readAsDataURL返回的值:

Media: recordVideo: base64File = {"__zone_symbol__state":null,"__zone_symbol__value":[]}

没有关于使用此文档的文档(我可以找到)。

2 个答案:

答案 0 :(得分:2)

如果问题是 File.readAsDataURL 没有返回响应也没有捕获错误,则将cordova.js移到vendor.js脚本之后(在index.html中)。我在ionic 3应用程序中遇到了这个问题。我通过此链接here解决了这个问题。

答案 1 :(得分:1)

函数readAsDataURL获取路径和文件名作为参数并返回一个promise。用法是

File.readAsDataURL("path_to_the_FileName", "Filename").then(result => {
  this.base64File = result;
});

根据控制台日志,文件名和文件名的完整路径是从数据中获取的(从MediaCapture.captureVideo返回的承诺)。

所以你可以使用它如下

var path = "file://"+data[0].fullPath.substring(7,data[0].fullPath.lastIndexOf("/"))‌​; 
File.readAsDataURL(path, data[0].name).then(result => { 
  this.base64File = result;
}