vue+element-ui+el-upload+ oss 阿里云上传视频和图片(前端处理)
1.安装 oss 依赖包
npm install ali-oss --save
2.新建 oss.js
let OSS = require('ali-oss')
export function client() { return new OSS({
region: '',
accessKeyId: '',
accessKeySecret: '',
bucket: ''
})
}
export const getFileNameUUID = () => {
function rx() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return `${+new Date()}_${rx()}${rx()}`
}
3.在页面中使用el-upload组件
<el-form-item label="视频/图片上传" prop="Video">
<el-upload action :http-request="Upload" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove"
:on-success="handleSuccess" :on-exceed="handleExceed" drag :limit="limit" :file-list="fileList">
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
</el-upload>
<el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
</el-form-item>
4.在script标签中引入刚才新建的oss.js文件
import {client,getFileNameUUID} from "../stroe/oss";
export default {
name: "Upload",
props: {
limit: {
type: Number,
default: 1
}
},
data(){
return {
fileList: [],
showProgress: false,
dataObj: {},
progress: 0
}
}
}
5.在methods中定义方法
handleExceed(files, fileList) {
this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
},
handlePreview(file) {},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
handleRemove(file, fileList) {},
handleSuccess(response, file, fileList) {
this.fileList = fileList;
},
beforeAvatarUpload(file) {
const isLt100M =
file.size / 1024 / 1024 > 10 && file.size / 1024 / 1024 < 1024;
const isLt30 = file.name.length < 30;
if (["video/mp4"].indexOf(file.type) == -1) {
this.$message.error("请上传正确的视频格式");
return false;
}
if (!isLt100M) {
this.$message.error("上传视频大小要在10MB~1GB之间哦!");
return false;
}
if (!isLt30) {
this.$message.error("上传视频文件名称长度必须要小于30个文字哦!");
return false;
}
},
Upload(file) {
const that = this;
async function multipartUpload() {
let temporary = file.file.name.lastIndexOf(".");
let fileNameLength = file.file.name.length;
let fileFormat = file.file.name.substring(
temporary + 1,
fileNameLength
);
let fileName = getFileNameUUID() + "." + fileFormat;
client(that.dataObj)
.multipartUpload(`image/${fileName}`, file.file, {
progress: function(p) {
console.log(p);
that.showProgress = true;
that.progress = Math.floor(p * 100);
}
})
.then(result => {
console.log(result);
})
.catch(err => {
console.log("err:", err);
});
}
multipartUpload();
}
6.oss阿里云
(一)申请创建bucket
[创建bucket](https://jingyan.baidu.com/article/4dc40848d5226988d846f174.html)
获取 [bucket] {String}:通过控制台或PutBucket创建的bucket。
[region] {String}:bucket所在的区域, 默认oss-cn-hangzhou。
(二)申请创建accessKey
[accessKeyId] {String}:通过阿里云控制台创建的AccessKey。
[accessKeySecret] {String}:通过阿里云控制台创建的AccessSecret。
[创建accessKey](https://jingyan.baidu.com/article/8275fc86f2c6bb06a13cf674.html)
7.因为前端直接处理,所以将accessKeyId,accessKeySecret直接暴露不利于安全,后续可以添加stsToken给一个时效性