ionic 压缩和上传视频文件
通过 Video Editor 插件压缩视频文件,然后使用 File 插件 转为 Blob 文件
依赖
- 安装File插件
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file
复制代码
- 安装Video Editor插件
ionic cordova plugin add cordova-plugin-video-editor
npm install @ionic-native/video-editor
复制代码
使用
- 导入 VideoEditor 插件和 File 插件
import { VideoEditor } from '@ionic-native/video-editor';
import { File } from '@ionic-native/file';
constructor(private videoEditor: VideoEditor,private file: File) { }
复制代码
-
使用 Camera 选择视频或 MediaCapture 录制视频
-
传入视频文件路径,返回压缩后视频文件的路径
async transcodeVideo(path: string):Promise<string>{
const fileUri = path.startsWith('file://') ? path : `file://${path}`;
const videoInfo = await this.videoEditor.getVideoInfo({ fileUri });
let width: number;
let height: number;
// 视频比例
const ratio = videoInfo.width / videoInfo.height;
if (ratio > 1) {
width = videoInfo.width > 480 ? 480 : videoInfo.width;
} else if (ratio < 1) {
width = videoInfo.width > 360 ? 360 : videoInfo.width;
} else if (ratio === 1) {
width = videoInfo.width > 480 ? 480 : videoInfo.width;
}
height = +(width / ratio).toFixed(0);
return this.videoEditor.transcodeVideo({
fileUri,
outputFileName: `${Date.now()}`,
outputFileType: this.videoEditor.OutputFileType.MPEG4,
width,
height
});
}
复制代码
- 把压缩后的视频转成 Blob
async readAsDataURL(path: string): Promise<string> {
const paths = path.split(/\//);
const fileName = paths[paths.length - 1];
let url = path.replace(fileName, '');
url = url.startsWith('file://') ? url : `file://${url}`;
return this.file.readAsDataURL(url, fileName);
}
复制代码
dataURLtoBlob(dataURL: string): Blob {
const arr = dataURL.split(',');
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const type = arr[0].match(/:(.*?);/)[1];
return new Blob([u8arr], { type });
}
复制代码
- 使用 FormData 上传视频文件