创建组件:testUpload.vue
<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
drag
list-type="picture"
:before-upload="beforeUpload"
:http-request="handleHttpRequest"
:limit="files"
:disabled="disabled"
multiple
action=""
:on-remove="onRemoveChange"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>
<script type="text/ecmascript-6">
import OSS from 'ali-oss'
import request from '@/router/axios';
import { imgUrl } from '@/config/env' //预览图片的前缀
//将渲染的内容导出
export default{
data(){
return {
region: 'oss-cn-shenzhen',
bucket: '', //这里选择OSS容器
url: '',//后台获取token地址
ClientObj: null,
dataObj: {},
files: 10,
disabled: false,
}
},
props:['fileList'],
methods: {
getDate(){
const date = new Date(),
year = date.getFullYear(),
month = date.getMonth() > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`,
day = date.getDate() > 9 ? date.getDate() : `0${date.getDate()}`,
hh = date.getHours() > 9 ? date.getHours() : `0${date.getHours()}`,
mm = date.getMinutes() > 9 ? date.getMinutes() : `0${date.getMinutes()}`;
return `${year}${month}${day}${hh}${mm}`;
},
getAliToken(){ //获取Token
return new Promise((resolve, reject) => {
request({
method: 'GET',
url: this.url
}).then(res => {
console.log(res)
if (res.data.code == 200) {
const {bucketName, accessKeyId, accessKeySecret, securityToken} = res.data.data;
this.dataObj = {
'region': this.region,
'bucket': bucketName,
'accessKeyId': accessKeyId,
'accessKeySecret': accessKeySecret,
'stsToken':securityToken,
'secure':true
};
resolve(true);
} else {
reject(false);
}
}).catch(err => {
console.log(err);
reject(false);
})
})
},
beforeUpload(file){
return new Promise((resolve, reject) => {
this.getAliToken().then(response => {
if (response) {
resolve(response);
} else {
reject(response);
}
}).catch(err => {
console.log(err);
reject(err);
});
})
},
async handleHttpRequest(option){ //上传OSS
console.log(this.dataObj)
try {
let vm = this;
vm.disabled = true;
const file = option.file;
//随机命名
const random_name = 'vsdwq/'+this.random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop();
new OSS(this.dataObj).multipartUpload(random_name, file).then(res=>{
console.log(res)
let obj = {
fileList : [{ 'name': res.name, 'url': imgUrl + res.name }],
img:res.name
}
this.$emit('successImg',obj)
this.$message({
showClose: true,
message: '上传成功',
type: 'success'
});
vm.disabled = false;
}).catch(err=>{
console.log(err)
this.disabled = false;
this.$message({
showClose: true,
message: '上传失败',
type: 'error'
});
})
} catch (error) {
console.error(error);
this.disabled = false;
this.$message({
showClose: true,
message: '上传失败',
type: 'error'
});
}
},
// 随机生成文件名
random_string(len) {
len = len || 32;
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678', maxPos = chars.length, pwd = '';
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
},
onRemoveChange(file, fileList){ //点击上传图片列表× 清空
this.$emit('onremove',{fileList:[],bannerImg:''})
}
},
}
</script>
<style>
/**渲染内容的样式**/
.el-upload-dragger{
background-color: #fff;
border-radius: 6px;
box-sizing: border-box;
text-align: center;
position: relative;
overflow: hidden;
border:none;
width: auto;
height: auto;
}
.el-upload__tip{
margin-top: 0;
}
</style>
使用
<template>
<div>
<testUpload :fileList="fileList" @onremove="onremove" @successImg="successImg" />
</div>
</template>
<script>
import request from '@/router/axios';
import testUpload from '../components/testUpload';
import { imgUrl } from '@/config/env'
export default {
name:'',
data(){
return {
fileList: [],
}
},
components:{testUpload },
methods: {
successImg(res){
console.log(res)
this.fileList = res.fileList
},
onremove(res){
console.log(res)
this.fileList = res.fileList
}
}
}
</script>
<style scope>
#banner{
padding: 20px 40px;
background: #fff;
}
.el-upload-list{
width: 60%;
}
.el-table th>.cell{
color: #000;
}
.el-table--border th{
background: #fafafa;
}
.upload-box{
position: relative;
display: inline-block;
cursor: pointer;
}
.fileclass{
opacity: 0;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
.BANNER{
height: 80%;
overflow: auto;
}
.BANNER::-webkit-scrollbar{
width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
height: 1px;
}
.BANNER::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
border-radius: 10px;
background: rgba(144,147,153,.5);
}
.BANNER::-webkit-scrollbar-track {/*滚动条里面轨道*/
border-radius: 10px;
background: #fff;
}
</style>