【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);
		});
    })
} 
相关推荐
以对_1 小时前
uview表单校验不生效问题
前端·uni-app
顶顶年华正版软件官方2 小时前
IDM下载器如何下载网盘文件 IDM下载器支持哪些网盘
阿里云·腾讯云·idm
cuijiecheng20182 小时前
音视频入门基础:FLV专题(13)——FFmpeg源码中,解析任意Type值的SCRIPTDATAVALUE类型的实现
ffmpeg·音视频
Envyᥫᩣ3 小时前
《ASP.NET Web Forms 实现视频点赞功能的完整示例》
前端·asp.net·音视频·视频点赞
HJ_SDK10 小时前
探索私有化聊天软件:即时通讯与音视频技术的结合
音视频
小雨cc5566ru12 小时前
uniapp+Android面向网络学习的时间管理工具软件 微信小程序
android·微信小程序·uni-app
二十雨辰17 小时前
[uni-app]小兔鲜-04推荐+分类+详情
前端·javascript·uni-app
jndingxin21 小时前
OpenCV视频I/O(8)视频采集类VideoCapture之从视频源中读取一帧图像函数read()的使用
人工智能·opencv·音视频
小雨cc5566ru21 小时前
hbuilderx+uniapp+Android健身房管理系统 微信小程序z488g
android·微信小程序·uni-app
敲啊敲952721 小时前
uni-app之旅-day02-分类页面
前端·javascript·uni-app