<template>
<div>
<el-upload :on-preview="preview" :on-remove="handleRemove" :on-change="changeFile" :before-upload="beforeUpload" :file-list="fileList" :http-request="upload" :limit="1" list-type="picture-card" action="#" :class="{ disabled:fileComputed }">
<i class="el-icon-plus"></i>
</el-upload>
<el-progress v-if="showPercent" style="width:180px" :percentage="percent" />
<el-dialog title="图片" :visible.sync="showDialog">
<img :src="imgUrl" alt="" style="width:100%">
</el-dialog>
</div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
SecretId: 'AKIDli7IFxEdb46tRjFsSloeHfBUYHno6kuq',
SecretKey: 'hBQVXO0OacW7ORotlQq7A1i9PRFrEl3N'
});
export default {
data() {
return {
fileList: [],
showDialog: false,
imgUrl: '',
currentFileUid: '',
percent: 0,
showPercent: false,
}
},
computed: {
fileComputed() {
return this.fileList.length === 1
}
},
methods: {
preview(file) {
console.log(file,'files');
this.imgUrl = file.url
this.showDialog = true
},
handleRemove(file) {
this.fileList = this.fileList.filter(item => item.uid !== file.uid)
},
changeFile(file, fileList) {
this.fileList = fileList.map(item => item)
},
beforeUpload(file) {
const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
if (!types.includes(file.type)) {
this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
return false
}
const maxSize = 5 * 1024 * 1024
if (maxSize < file.size) {
this.$message.error('图片大小最大不能超过5M')
return false
}
this.currentFileUid = file.uid
this.showPercent = true
return true
},
upload(params) {
if (params.file) {
cos.putObject({
Bucket: 'hr-106-1305528766',
Region: 'ap-shenzhen-fsi',
Key: params.file.name,
StorageClass: 'STANDARD',
Body: params.file,
onProgress: (params) => {
this.percent = params.percent * 100
},
}, (err, data) => {
console.log(err || data);
if (!err && data.statusCode === 200) {
console.log(1);
console.log(this.fileList);
this.fileList = this.fileList.map(item => {
if (item.uid === this.currentFileUid) {
return { url: 'http://' + data.Location, upload: true }
}
return item
})
setTimeout(() => {
this.showPercent = false
this.percent = 0
}, 1000)
}
})
}
}
},
}
</script>
<style>
.disabled .el-upload--picture-card {
display: none;
}
</style>