我一直在寻找解决方案。我按如下方式解决此问题。
在platform.ready()
函数之后,我创建了一个目录,如下所示。
this.file.createDir(this.file.externalDataDirectory , 'Videos', false).then(() => {
// console.log('Directory created successfully');
}).catch(() => {
// console.log('Failed to create directory');
});
在创建的目录中下载视频
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Diagnostic } from '@ionic-native/diagnostic';
...
constructor(private diagnostic: Diagnostic,
private transfer: FileTransfer, private file: File)
download(item) {
let downloadProgress: any;
const fileTransfer: FileTransferObject = this.transfer.create();
const url = encodeURI(item.url);
const targetPath = this.file.externalDataDirectory + 'Videos/' + item.title + '.mp4';
this.diagnostic.requestCameraAuthorization(true).then(() => {
fileTransfer.download(url, targetPath, true).then((entry) => {
// console.log('download complete: ' + entry.toURL());
}, (error) => {
console.log(error);
});
fileTransfer.onProgress((progress) => {
downloadProgress = Math.round((progress.loaded / progress.total) * 100) + '%';
console.log('Downloading progress ...', downloadProgress);
});
}, (error) => {
console.log(error);
});
}
这会在创建的文件夹中下载一个文件Videos
。您实际上可以通过Android/data/com.your.app/files/
.
如果您正在使用android
但不起作用,请在file.setReadable(true, false);
里面添加FileTransfer.java
.
播放视频以供离线使用 确保这些行存在于index.html
<meta http-equiv="Content-Security-Policy" content="style-src 'self' 'unsafe-inline'; media-src *; connect-src *">
在你的config.xml
文件中
<access origin="*" />
<allow-navigation href="*" />
<allow-navigation href="http://*/*" />
<allow-navigation href="file://*/*" />
<access origin="cdvfile://*" />
<allow-intent href="*" />
<access origin="*" />
如果不添加它们。
然后最后在您的视频播放器页面中
<video id="video" controls="controls" preload="metadata" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source [src]="content" type="video/mp4" />
</video>
并且在组件中
ionViewDidEnter() {
this.file.listDir(this.file.externalDataDirectory, 'Videos')
.then((data) => {
console.log(data[0]);
this.count = data.length;
const src = data[0].toInternalURL();
this.file.resolveLocalFilesystemUrl(src).then(data => {
this.content = data.toURL();
document.getElementById('video').setAttribute('src', this.content);
console.log('Content path cahnged ', this.content);
}, error => {
console.log('File path error');
})
})
.catch(err => console.log('Directory doesnt exist'));
}
就是这样。我希望这行得通。