vue2实现视频文件直传阿里云OSS完整详细代码步骤

阿里云对象存储服务OSS是阿里提供的一种对象存储服务,也是目前市面上最常用的三方对象存储服务之一。

随着如今视频和图片的大量使用,网站及应用开发中如果将大量的图片和视频放在自己服务器势必会加大企业的运营成本。这时候第三方对象存储服务就成了好的解决方案。

本篇文章就来介绍在vue2中如何使用阿里云对象存储服务OSS,实现前端方式将视频等文件数据直接存储到阿里云OSS中。完整步骤如下:

一、安装ali-oss

npm install ali-oss --save

二、页面中引入并使用

    2.1、单页面引入ali-oss

import OSS from "ali-oss";

    2.2、上传file文件

<input  ref="fileInput" type="file" @change="handleFileChange" />

    2.3、公用方法直传阿里云OSS

async handleFileChange() {
//上传的文件
const file = this.$refs.fileInput.files[0]; // 获取input file选择的文件
let timestamp = Date.parse(new Date());
let date = new Date(timestamp);
let Y = date.getFullYear(); //年
let M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; //月
let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //日
let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //时
let m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //分
let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
let tempFormat = file.name.substring(file.name.lastIndexOf(".") + 1);
let filePath = "upload/video/" + Y + M + D + "/" + Y + M + D + h + m + s + "." + tempFormat;
//阿里云直传
const client = new OSS({
region: '', // 设置Bucket所在地域,例如'oss-cn-hangzhou'
accessKeyId: '',
accessKeySecret: '',
bucket: '', // 设置Bucket名称//存储空间
});
const result = await client.put(filePath, file); // 上传文件到指定的路径下
console.log("Upload result:", result); // 打印上传结果,包含文件的URL等信息
}

参数说明:

    accessKeyId,accessKeySecret:AccessKey ID和AccessKey Secret组成的一组密钥对。

    bucket:Bucket名称//存储空间

    region:设置Bucket所在地域

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!