项目场景:
uniapp 上传视频阿里OSS对象存储
需求描述:
H5移动端开发中需要用户上传2秒左右视频的需求时。需要将视频上传至阿里oss中存储,并且下载到当前页面进行展示。
解决方案:
需要用到的依赖包:
npm install ali-oss --save
创建一个 upload.js 文件:
const OSS = require("ali-oss"); //引入安装包;
//配置 阿里 oss 存储对应的 bucket 桶
var client = new OSS({
region: "oss-cn-beijing", //指申请OSS服务时的地域
endpoint: "https://oss-cn-beijing.aliyuncs.com", //指定为HTTPS,也可以是IP的形式 region将会被忽略
accessKeyId: "xxxxxxxxxxxxxxxxxx", // 填写你的accessKeyId
accessKeySecret: "xxxxxxxxxxxxxxxxxxxxx", // 填写你的accessKeySecret
bucket: "xxxx", // 桶的名称
secure: true // 配合region使用。如果指定secure为true,则使用HTTPS访问。
});
// e : 文件对象,filename:存储文件名
export function uploadVid(e, filename) {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '正在上传...'
});
if (e.tempFile.length == 0) {
uni.hideLoading();
uni.showToast({
title: '未找到视频',
icon: 'none'
})
return false;
};
let file = e.tempFile;
if (file.size > 20971520) { // 20M
uni.showToast({
title: "您上传的视频文件过大,请重新上传1-2秒的人脸视频!",
icon: "none"
});
return false
}
let time = new Date(),
y,
m,
d;
y = time.getFullYear();
m = String(time.getMonth() + 1).length === 2 ?
time.getMonth() + 1 :
"0" + (time.getMonth() + 1);
d = tring(time.getDate()).length === 2 ?
time.getDate() :
"0" + time.getDate();
let dfilefold = y + m + d;
let r = Math.random().toString(16).substr(2);
let name = filename + dfilefold + "/" + r + ".mp4";
client.multipartUpload(name, file).then(function(result) {
uni.hideLoading();
uni.showToast({
title: "上传成功,请点击提交",
icon: "none"
})
let url = result.res.requestUrls[0];
var index = url.indexOf("?");
url = url.substring(0, index);
resolve(url);
})
.catch((err) => {
uni.hideLoading();
uni.showToast({
title: "上传失败",
icon: "none"
})
reject(err)
});
}).catch(err => {
reject(err)
})
}
在uniapp 项目组件中
<template>
<view class="">
<view class="">
视频认证(上传1-2秒左右人脸视频):
</view>
<view class="">
<video style="height: 310rpx;" :src="personVideo" controls />
<button @tap="uploadVidfn('realname/')">上传视频</button>
</view>
</view>
</template>
<script>
import {uploadVid} from "../utils/upload.js";
export default {
data() {
return {
personVideo: "",
};
},
methods:{
// 选择视频上传
uploadVidfn(filename) {
let that = this;
uni.chooseVideo({
success: (res) => {
uploadVid(res, filename).then(res => {
that.personVideo = res;
});
}
})
},
}
</script>
点赞 评论 收藏 ~~ 有疑惑的小伙伴,可能是我表达不清楚,可以留言讨论,如有错误,也希望大家不吝指出。 ~~ 点赞 评论 收藏