前言:发现项目中超过1个G视频上传到oss会失败,没办法做了个oss分片上传,记录一下
<template>
<div class="app-container">
<el-row>
<el-col :span="5" :offset="10">
<el-upload
ref="upload"
drag
action=""
:limit="1"
:http-request="handleVideoUpload"
:on-remove="handleRemove"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
<el-progress
:percentage="percentage"
:status="uploadStatus"
v-if="percentage > 0 && percentage <= 100"
></el-progress>
</el-col>
<el-col :span="5" :offset="4">
<video
:src="videoURL"
v-if="videoURL"
style="width: 100%; height: 100%"
controls
></video>
</el-col>
</el-row>
</div>
</template>
<script>
// 引入ali-oss插件
import OSS from "ali-oss";
const client = new OSS({
region: "oss-cn-xxxx", // 地区节点
accessKeyId: "xxxxxxx", // Access Key ID
accessKeySecret: "xxxxxxxx", // Access Key Secret
bucket: "xxxx", // Bucket名称
});
export default {
data() {
return {
// 进度条上传状态 el-progress
uploadStatus: null,
// 进度条百分比
percentage: 0,
// 视频预览地址
videoURL: "",
};
},
methods: {
/**
* @description: 文件列表移除文件时的钩子 function(file, fileList) 1.删除文件的时候对视频上传进行停止 ,进行数据的重置
* @param {*}
* @return {*}
*/
handleRemove(file, fileList) {
this.percentage = 0;
this.uploadStatus = null;
this.videoURL = "";
},
/**
* @description: 自定义的视频上传方法
* @param {*}
* @return {*}
*/
handleVideoUpload(data) {
console.log(data, "handleVideoUpload");
this.multipartUpload(data);
},
/**
* @description: 自定义视频上传的方法 分片上传
* @param {*}
* @return {*}
*/
async multipartUpload(data) {
console.log(data, "file");
try {
// data.file.name 文件名 videos/${data.file.name} 代表 上传到oss服务器上 videos文件夹下面
// data.file 文件流
// progress 视频上传进度函数
const result = await client.multipartUpload(
`videos/${data.file.name}`,
data.file,
{
progress: (p, checkpoint) => {
console.log(p, checkpoint, "checkpoint");
if (!checkpoint) {
this.percentage = 100;
return;
}
// 上传进度,由于p 是多位小数,所以保留一位小数
this.percentage = parseFloat((p * 100).toFixed(1));
},
// 设置分片大小。默认值为1 MB,最小值为100 KB。我设置的是10M一个分片
partSize: 1024 * 1024 * 1,
}
);
const { res } = result;
console.log(result, "result");
if (res.statusCode === 200) {
this.videoURL = res.requestUrls[0].split("?")[0];
}
} catch (e) {
console.log(e, "e");
// 捕获超时异常。
if (e.code === "ConnectionTimeoutError") {
this.uploadStatus = "exception";
}
}
},
},
};
</script>