<template>
<div>
<el-upload
list-type="picture-card"
:file-list="fileList"
:on-preview="preview"
:on-remove="handleRemove"
:on-change="changeFile"
:before-upload="beforeUpload"
:http-request="upload"
action="#"
:class="{disabled: fileComputed}"
>
<i class="el-icon-plus" />
</el-upload>
<el-progress v-if="showPercent" :percentage="percent" style="width: 180px" />
<el-dialog :visible.sync="showDialog" title="图片预览">
<img :src="imgUrl" alt style="width:100%" />
</el-dialog>
</div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
import { defineComponent, reactive, toRefs } from 'vue'
const cos = new COS({
SecretId: 'AKIDfFafT0GGzRcW8TXLs87rLYT8SWJp54mD',
SecretKey: 'B5i49xUkjRt3wYtxkGUR7WfX8SVIn1zg'
})
export default defineComponent({
setup() {
const state = reactive({
showPercent: false,
percent: 0,
showDialog: false,
imgUrl: '',
fileList: []
});
const preview = (file) => {
state.imgUrl = file.url
state.showDialog = true
};
const handleRemove = (file) => {
state.fileList = state.fileList.filter(item => item.uid !== file.uid)
};
const changeFile = (file, fileList) => {
state.fileList = fileList.map(item => item)
};
const beforeUpload = (file) => {
const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png'];
if (!types.includes(file.type)) {
Message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!');
return false;
};
const maxSize = 25 * 1024 * 1024;
if (maxSize < file.size) {
Message.error('图片最大的大小为5M');
return false;
};
return true;
};
const upload = (params) => {
if (params.file) {
state.showPercent = true
cos.putObject({
Bucket: 'trumpdown-1302806742',
Region: 'ap-beijing',
Key: params.file.name,
StorageClass: 'STANDARD',
Body: params.file,
onProgress: (progressData) => {
state.percent = progressData.percent * 100
}
}, (err, data) => {
console.log(err)
if (data.statusCode === 200 && data.Location) {
console.log(state.fileList)
state.fileList = state.fileList.map(item => {
if (item.uid === params.file.uid) {
return { url: 'http://' + data.Location, upload: true }
}
return item
})
state.showPercent = false
state.percent = 0
}
})
}
};
return {
...toRefs(state),
preview,
handleRemove,
changeFile,
beforeUpload,
upload
};
},
computed: {
fileComputed() {
return this.fileList.length === 1
}
}
})
</script>
<style>
.disabled .el-upload--picture-card {
display: none;
}
</style>