uniapp----upload pictures and videos to Tencent Cloud COS

uniapp----upload pictures and videos to Tencent Cloud COS

1. Go to the official website to download cos-wx-sdk-v5.min.js, and quote it. Full code:

import func from '@/config/func.js';
import {
    
    
	myRequest
} from '@/config/api.js';

var COS = require('./cos-wx-sdk-v5.min');
const config = {
    
    
	Bucket: 'XXXXXXXXX', // 存储桶的名称,命名规则为 BucketName-APPID,此处填写的存储桶名称必须为此
	Region: 'xxxxx', // 存储桶所在地域
	https: 'https://'
};


var cos = new COS({
    
    
	// ForcePathStyle: true, // 如果使用了很多存储桶,可以通过打开后缀式,减少配置白名单域名数量,请求时会用地域域名
	SimpleUploadMethod: 'putObject', // 强烈建议,高级上传、批量上传内部对小文件做简单上传时使用putObject,sdk版本至少需要v1.3.0
	getAuthorization: function(options, callback) {
    
    
		// 初始化时不会调用,只有调用 cos 方法(例如 cos.putObject)时才会进入
		// 异步获取临时密钥	
		myRequest('getTencentUploadToken', 'POST', {
    
    
			bucket: config.Bucket,
			region: config.Region,
		}).then(result => {
    
    
			let data = result.data;
			let credentials = data && data.credentials;
			if (!data || !credentials) return console.error('credentials invalid');
			callback({
    
    
				TmpSecretId: credentials.tmpSecretId,
				TmpSecretKey: credentials.tmpSecretKey,
				// v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
				SecurityToken: credentials.sessionToken,
				// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
				StartTime: data.startTime, // 时间戳,单位秒,如:1580000000
				ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000900
			});
		})

	}
});


// 选择图片
const uniChooseImage = () => {
    
    
	return new Promise((resolve, rejct) => {
    
    
		uni.chooseImage({
    
    
			// 从本地相册选择图片或使用相机拍照。
			count: 1, //默认选择1张图片
			sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
			success: res1 => {
    
    
				resolve(res1.tempFilePaths[0]);

			}
		});
	});
}
// 上传视频封面图片 腾讯云
const cosUpLoadimg = async () => {
    
    
	let file = '';
	let promise;
	// 获取临时路径
	await uniChooseImage().then(res => {
    
    
		file = res
	})
	await myRequest('getTencentUploadFilename', 'POST', {
    
    
		file_name: file
	}).then(v => {
    
    
		let keyz = v.data; //获取腾讯cos上传文件名
		promise = new Promise((resolve, rejct) => {
    
    
			func.loading("上传中...")
			// 微信小程序里获取文件管理器
			var wxfs = uni.getFileSystemManager();
			wxfs.readFile({
    
    
				filePath: file,
				success: function(res) {
    
    
					cos.putObject({
    
    
						Bucket: config.Bucket,
						Region: config.Region,
						Key: keyz,
						Body: res.data, // Body里传入的是文件内容
					}, (err, data) => {
    
    
						
						if (data.statusCode == 200) {
    
    
							let datas = {
    
    
								coverImgAll: config.https + data
									.Location,
								coverImg: keyz
							}
							resolve(datas);
						} else {
    
    
							func.alert('请重新上传!');
						}
						uni.hideLoading();
					});
				},
				fail: function(err) {
    
    
					uni.hideLoading();
					rejct(err)
					console.error(err)
				},
			});

		});

	})
	return promise;
};


// 选择视频
const uniChoosevideo = () => {
    
    
	return new Promise((resolve, rejct) => {
    
    
		uni.chooseVideo({
    
    
			sourceType: ['album'],
			success: function(res) {
    
    
				resolve(res.tempFilePath);
				
				// self.src = res.tempFilePath;
			}
		});
	});
}

// 上传视频 到腾讯云
const cosChoosevideo = async () => {
    
    
	let uploadFile = '';
	let promise;
	await uniChoosevideo().then(res => {
    
    
		uploadFile = res
	})
	await myRequest('getTencentUploadFilename', 'POST', {
    
    
		file_name: uploadFile
	}).then(v => {
    
    
		let keyz = v.data;//获取腾讯cos上传文件名
		promise = new Promise((resolve, rejct) => {
    
    
			func.loading("上传中...");
			var wxfs = uni.getFileSystemManager();
			wxfs.readFile({
    
    
				filePath: uploadFile,
				success: function(res) {
    
    
					cos.putObject({
    
    
						Bucket: config.Bucket,
						Region: config.Region,
						Key: keyz, //临时路径 后台截取获取
						Body: res.data, // Body里传入的是文件内容
					}, (err, data) => {
    
    
						if (data.statusCode == 200) {
    
    
							let datas = {
    
    
								videoUrl: config.https + data.Location,
								video_link: keyz
							}
							resolve(datas);
							
							console.log('www', datas);
						}else {
    
    
							func.alert('请重新上传!');
						}
						uni.hideLoading();
					});
				},
				fail: function(err) {
    
    
					uni.hideLoading();
					rejct(err)
					console.error(err)
				},
			});
		});		
	})	
	return promise;
}
module.exports = {
    
    
	cosChoosevideo,
	cosUpLoadimg
}

2. Call it in the page you need

import upFile from '@/config/upFile.js';
// 上传视频或者封面
upFileBtn(tag) {
    
    
	if (tag == 1) {
    
     //视频 腾讯云
		upFile.cosChoosevideo().then(v => {
    
    
			this.videoUrl = v.videoUrl;
			this.video_link = v.video_link;
		})
	}
	if (tag == 2) {
    
     //上传图片 腾讯云
		upFile.cosUpLoadimg().then(v => {
    
    
			this.coverImg = v.coverImg;
			this.coverImgAll = v.coverImgAll;
		})
	}

},

Guess you like

Origin blog.csdn.net/heavenz19/article/details/129708899