element-ui拖拽上传及问题解决(drag的使用注意事项)
上传组件(:drag=“true”)
<template>
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:http-request="uploadImage"
:drag="true"
>
<img v-if="value" :src="value" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</template>
<script>
import COS from 'cos-js-sdk-v5'
export default {
props: {
value: {
type: String,
required: true
}
},
methods: {
uploadImage(e) {
console.log(e) // 上传的图片是e.file
console.log(e.file)
const cos = new COS({
SecretId: 'AKID4zhBRirnVyCD0Zu1xfNs9XjiX9ZkhPrw',
SecretKey: 'xhDUbVCftyrY3NXbVEpGVWK0UkmaFiCi'
}) // 完成cos对象的初始化
cos.putObject(
{
Bucket: 'web90-1318397310', // 存储桶名称
Region: 'ap-nanjing', // 地域名称
Key: e.file.name, // 文件名称
StorageClass: 'STANDARD', // 固定值
Body: e.file // 文件对象
},
(err, data) => {
if (data.statusCode === 200 && data.Location) {
console.log(data)
// 拿到了腾讯云返回的地址
// 通过input自定义事件将地址传出去
this.$emit('input', 'http://' + data.Location) // 将地址返回了
} else {
this.$message.error(err.Message) // 上传失败提示消息
}
}
)
},
handleAvatarSuccess(res, file) {
// this.imageUrl = URL.createObjectURL(file.raw)
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.el-upload-dragger{
width: 180px;
height: 180px;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
.avatar-uploader-darger {
width: 180px;
height: 180px;
}
</style>
官方使用
<el-upload
class="upload-demo"
drag
action="https://jsonplaceholder.typicode.com/posts/"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
注意:
在使用drag时,会在外边形成一个class='avatar-uploader-darger’的盒子,并且该盒子宽度会变成原来的2倍.
解决方法:
在css样式中,找到类名为avatar-uploader-darger的盒子重新设置宽度,
例如:
.avatar-uploader-darger {
width: 180px;
height: 180px;
子宽度会变成原来的2倍.
解决方法:
在css样式中,找到类名为avatar-uploader-darger的盒子重新设置宽度,
例如:
.avatar-uploader-darger {
width: 180px;
height: 180px;
}