【uniapp】阿里云OSS上传 [视频上传]

引用uniapp插件市场的插件,使用的是视频上传 (阿里云 oss上传)
我只使用了H5和App端,需要后端配置跨域
yk-authpup详情请参考 》》【用户告知权限申请的目的】
【插件市场】阿里云存储OSS前端直接上传(全端通用) - 前端JASON

html 复制代码
<template>
<view>
	<view class="bg pd-20-30">
		<view class="">
			<view class="mg-tb-25 fbc">上传视频
				<view v-if="editVideo" @click="delVideo" class="c-d41 font-26">删除</view>
			</view>
			<view class="bg-f57 mg-t-20 h-600">
				<progress class="file-picker__progress-item" :percent="vProgress" stroke-width="4" />
				<view v-if="editVideo" class="relative wh-100p">
					<video :autoplay="false" class="wh-100p" :src="editVideo" 
					:poster="editVideo+'?x-oss-process=video/snapshot,t_100,f_jpg'"></video>
				</view>
				<view v-if="!editVideo" @click="judgment('video')" class="t_c wh-100p fcc">
					<view class="">
						<uni-icons type="videocam" size="45" color="#d8d8d8"></uni-icons>
						<view class="font-25 c-cc spa_1" style="margin-top: -15rpx;">上传效果视频</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	<!-- 用户告知权限申请的目的,在App端上传视频图片等需要有权限提示(华为审核上架必备) -->
	<yk-authpup ref="authpup" :permissionID="permissionID" @changeAuth="changeAuth"></yk-authpup>
</view>
</template>

<script>
import { ossUpload } from '@/js_sdk/alioss-upload/oss.js'
export default {
	data() {
		return {
			editVideo: '',
			vProgress: 0,
			// 用户告知权限申请的目的
			changeType: '',
			soIndex: 0,
			permissionID:''
		};
	},
	methods: {
		judgment(_type) { // 判断H5还是App
			this.changeType = _type;
			// #ifdef APP-PLUS
			let that=this;
			that.permissionID = 'WRITE_EXTERNAL_STORAGE';
			if (plus.os.name == 'Android') setTimeout(()=>{ that.$refs['authpup'].open(); },200)
			if (plus.os.name == "iOS") that.changeAuth();
			// #endif
			// #ifdef H5
			this.changeAuth();
			// #endif
		},
		changeAuth() { //用户授权权限后的回调
			if(this.changeType =='video') this.chooseVideo();
		},
		chooseVideo() { // 上传视频
			let that=this;
			uni.chooseVideo({
				count: 1,
				sourceType: ['album'],
				success: async function (rey) {
					// console.log(rey)
					let _name;
					// #ifdef APP-PLUS
					_name = rey.tempFilePath;
					// #endif
					// #ifdef H5
					_name = rey.name;
					// #endif
					
					const {success,data} = await ossUpload(rey.tempFilePath, _name, 'uploads/video/',function(_ret){
						that.vProgress=_ret.progress
					});
					if(success){
						that.editVideo=data;
					} else{
						that.toast(data)
					}
					return
					uni.showLoading({ title: '上传中',mask: true });
					uni.uploadFile({
						url: that.uploadUrl,
						filePath: rey.tempFilePath,
						name: 'file',
						success: (uploadFileRes) => {
							let res = JSON.parse(uploadFileRes.data)
							uni.hideLoading();
							if(res.code==1){
								that.editVideo=res.data;
							} else{
								that.toast(res.msg)
							}
						},
					});
				},
				fail: (err) => { 
					console.log(err)
					if(plus.os.name == "iOS"&&err["errMsg"]=="chooseVideo:fail No filming permission"){
						setTimeout(()=>{ that.$refs['authpup'].open(); },200)
					}
				}
			});
		},
		delVideo() {
			this.editVideo=''; 
			this.vProgress=0;
		},
	}
};
</script>

<style>
image{ pointer-events: all; }
.video_cover{
	position: absolute; top: 0; left: 0; bottom: 0; z-index: 1;
	/* background-color: rgba(1,1,1,.5); */
}
</style>

js_sdk/alioss-upload文件下的js

oss.js

javascript 复制代码
import { Base64 } from './base64.js'
import { util } from './crypto.js'
import { HMAC } from './hmac.js'
import { SHA1 } from './sha1.js'

// ======下面这3个信息必填======
const url = '_您的URL_';
const OSSAccessKeyId = '_您的OSSAccessKeyId_';
const OssAccesskeySercet= '_您的OssAccesskeySercet_';
// console.log(uni.getStorageSync('aliossUp'))


const policyText = {
    "expiration": "2034-01-01T12:00:00.000Z", // 设置Policy的有效期,格式为UTC时间。如果Policy失效,将无法上传文件。
    "conditions": [
        ["content-length-range", 0, 1048576000] // 限制上传文件的大小,单位为字节,此处限制文件大小为1 GB。如果上传的文件大小超过此限制,文件将无法上传到OSS。如果未设置该限制,则默认文件大小最大为5 GB。
    ]
}

const policy = Base64.encode(JSON.stringify(policyText))
const bytes = HMAC(SHA1, policy, OssAccesskeySercet, { asBytes: true })
const signature = util.bytesToBase64(bytes)

// 生成文件名随机字符串
function random_string(len) {
    const strLeng = len || 32;
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
    const maxPos = chars.length;
    let pwd = '';
    for (let i = 0; i < strLeng; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

// 获取文件后缀
function get_suffix(filename) {
    const pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

// dir格式:'img/'
export const ossUpload = (filePath, name, dir,onUploadProgress) => {
    const key = dir + random_string(10) + get_suffix(name)
    return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
            url,
            filePath,
            name: 'file',
            formData: {
                name,
                key,
                policy,
                OSSAccessKeyId,
                success_action_status: '200',
                signature
            },
            success: () => {
                resolve({success: true, data: url+key})
            },
            fail: () => {
                reject({success: false, data: '上传失败'})
            }
        })
        // ======做了一些修改加了一个上传进度======
        uploadTask.onProgressUpdate((res) => {
            onUploadProgress(res)
			// console.log('上传进度' + res.progress);
			// console.log('已经上传的数据长度' + res.totalBytesSent);
			// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
		});
    })
} 
相关推荐
guai_guai_guai44 分钟前
uniapp
前端·javascript·vue.js·uni-app
划水小将军4 小时前
阿里云函数计算GBK编码
阿里云·云计算
EasyCVR5 小时前
EHOME视频平台EasyCVR视频融合平台使用OBS进行RTMP推流,WebRTC播放出现抖动、卡顿如何解决?
人工智能·算法·ffmpeg·音视频·webrtc·监控视频接入
阿伟来咯~6 小时前
一些 uniapp相关bug
uni-app·bug
冷凝女子7 小时前
【QT】海康视频及openCv抓拍正脸接口
qt·opencv·音视频·海康
安步当歌8 小时前
【WebRTC】视频编码链路中各个类的简单分析——VideoStreamEncoder
音视频·webrtc·视频编解码·video-codec
顾北川_野8 小时前
Android CALL关于电话音频和紧急电话设置和获取
android·音视频
顶呱呱程序8 小时前
2-143 基于matlab-GUI的脉冲响应不变法实现音频滤波功能
算法·matlab·音视频·matlab-gui·音频滤波·脉冲响应不变法
EasyCVR10 小时前
萤石设备视频接入平台EasyCVR多品牌摄像机视频平台海康ehome平台(ISUP)接入EasyCVR不在线如何排查?
运维·服务器·网络·人工智能·ffmpeg·音视频
runing_an_min10 小时前
ffmpeg 视频滤镜:屏蔽边框杂色- fillborders
ffmpeg·音视频·fillborders