- 下载 ali-oss
npm install ali-oss
- 封装oss上传工具 新建ali-oss.js
import http from './request' //接口请求封装
let OSS = require('ali-oss');
/**
* [region] {String}:bucket所在的区域, 默认oss-cn-hangzhou。
* [accessKeyId] {String}:通过阿里云控制台创建的AccessKey。
* [accessKeySecret] {String}:通过阿里云控制台创建的AccessSecret。
* [bucket] {String}:通过控制台或PutBucket创建的bucket。
*/
function ikjOss() {}
ikjOss.prototype.client = function (func) {
//请求后台获取秘钥
http.post('/oss', '').then(res => {
let client = new OSS({
region: res.data.region,
accessKeyId: res.data.accessKeyId,
accessKeySecret: res.data.accessKeySecret,
bucket: res.data.bucket
});
func(client);
}).catch(error => {
console.log('秘钥获取失败')
})
};
const ikj_oss = new ikjOss()
export default ikj_oss
- vue使用
<template>
<div class="oss">
<el-upload :before-remove="beforeRemove"
:before-upload="beforeAvatarUpload"
:file-list="fileList"
:http-request="upload"
:limit="limit"
:on-exceed="handleExceed"
:on-remove="handleRemove"
:on-success="handleSuccess"
action
class="upload-demo">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<el-progress :percentage="progress"
:stroke-width="15"
:text-inside="true"
v-show="showProgress">
</el-progress>
</div>
</template>
<script>
export default {
name: 'oss',
data() {
return {
fileList: [],//文件列
limit: 1, //最大上传文件数
showProgress: false,//进度条的显示
progress: 0 //进度条数据
};
},
methods: {
// 文件超出个数限制时的钩子
handleExceed(files, fileList) {
this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
},
// 删除文件之前的钩子
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
this.$emit('on-remove', file, fileList)
},
// 文件上传成功时的钩子
handleSuccess(response, file, fileList) {
this.fileList = fileList;
},
//文件上传前的校验
beforeAvatarUpload(file) {
const isLt100M =
file.size / 1024 / 1024 > 0 && file.size / 1024 / 1024 < 1024;
const isLt30 = file.name.length < 30;
if (file.type !== 'image/png') {
this.$message.error("请上传PNG格式图片");
return false;
}
if (!isLt100M) {
this.$message.error("上传大小要在0MB~1GB之间哦!");
return false;
}
if (!isLt30) {
this.$message.error("上文件名称长度必须要小于30个文字哦!");
return false;
}
},
//覆盖默认的上传行为,自定义上传的实现
upload(file) {
const that = this;
that.$oss.client(function (client) {
//client.multipartUpload('文件路径/文件名称','上传文件')
client.multipartUpload(`zsx/zsx`, file.file, {
progress: function (p) {
//p进度条的值
that.showProgress = true;
that.progress = Math.floor(p * 100);
}
}).then(result => {
//上传成功返回值,可针对项目需求写其他逻辑
that.$message({
message: '文件上传成功',
type: 'success'
});
console.log(result);
}).catch(err => {
that.$message.error('上传失败,请重试。');
console.log("err:", err);
});
})
}
}
}
</script>
网友评论