ionic2/3 保存 图片/视频到相册

需要插件实现:
文件系统插件 https://github.com/apache/cordova-plugin-file-transfer

--->安装插件
npm install --save @ionic-native/file-transfer

图片库插件 https://github.com/terikon/cordova-plugin-photo-library

--->安装插件
npm install --save @ionic-native/photo-library

在app.module.ts 中添加:

import { File } from '@ionic-native/file';
import { FileTransfer } from '@ionic-native/file-transfer';
import { PhotoLibrary } from '@ionic-native/photo-library';

providers: 下添加:
PhotoLibrary,
FileTransfer,
File,

在需要使用的ts 文件中:

import { File } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { PhotoLibrary } from '@ionic-native/photo-library';
declare let cordova:any; //ionic2 使用ionic1插件需要先声明

constructor(
private platform: Platform,
private transfer: FileTransfer,
private file: File,
private photoLibrary: PhotoLibrary

/****

  • 保存聊天图片到相册
  • @param imgPath 图片地址
    */

savePicture (imgPath) {
var album = 'xxx';
cordova.plugins.photoLibrary.saveImage(imgPath, album, (libraryItem)=> {
this.toast.create("图片保存成功");
}, (err)=> {
console.log(err);
});

}

/**

  • 保存聊天视频到相册
  • @param videoPath 视频地址
    */
    saveVideo(videoPath) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    fileTransfer.download(videoPath,this.file.dataDirectory + 'file.mp4').then((entry) => {
    console.log('download complete: ' + entry.toURL());
    cordova.plugins.photoLibrary.saveVideo(entry.toURL(), 'xxx', (success)=> {
    this.toast.create("视频保存成功!");
    }, (err)=> {
    if (err.startsWith('Permission')) {
    cordova.plugins.photoLibrary.requestAuthorization(function() {
    }, function(err) {
    this.toast.create("Oops! unable to save video, please try after sometime.", "long", "center");
    // User denied the access
    }, // if options not provided, defaults to {read: true}.
    {
    read: true,
    write: true
    });
    }
    });
    }, err=> {
});

}

总结: 下载图片只需要 cordova.plugins.photoLibrary.saveImage 即可,但是下载视频需要先保存文件到本地,才能保存到相册:
fileTransfer.download(videoPath,this.file.dataDirectory + 'file.mp4').then((entry) => {
console.log('download complete: ' + entry.toURL());
cordova.plugins.photoLibrary.saveVideo(entry.toURL(),

且: iOS 保存视频对格式有要求,提供的视频不能是.webm。使用.mov或.mp4。

注: this.toast.create("XXXXX" )为另一种下载的提示信息的插件,安装方法同上面2个插件。

你可能感兴趣的:(ionic2/3 保存 图片/视频到相册)