第一幕
使用elementUI做只能上传一张图片上传图片功能按钮的时候发现,普通的默认上传无法正确支持支持正确请求接口完成图片的上传,于是决定使用自定义上传的方式…
// 主要代码
<el-upload size="small" class="upload-demo" action="#" :headers="uploadProHeader"
:http-request="handleMiniUpload"
:before-upload="beforeMiniUpload"
:on-remove="deleteMiniproImg"
:on-change="uploadMiniChange" list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload-tip el-upload-tip--small">
请上传小于2MB的png/jpg/jpeg图片,建议尺寸520*416
</div>
</el-upload>
......
methods: {
// 图片格式进行校验提示,大小不能超过2M
beforeMiniUpload (file) {
const types = ['image/jpeg', 'image/jpg', 'image/png']
const testmsg = types.includes(file.type)
const isLt10M = file.size < 1024 * 1024 * 2
if (!testmsg) {
this.$message.error('上传图片格式不支持!')
return false
}
if (!isLt10M) {
this.$message.error('上传图片大小不能超过2MB!')
this.deleteMiniproImg()
return false
}
},
// 做上传动作,取得上传成功后接口返回的数据
handleMiniUpload (params) {
const file = params.file
var formData = new FormData()
formData.append('file', file)
serviceMessageApi.uploadImg(this.$route.params.appid, formData).then(res => {
if (+res.code === 0) {
...... // 取得接口我们所需要的数据
}
})
},
// 删除图片之后把对应数据删除
deleteMiniproImg () {
...
},
}
第二幕
做完这些发现,当用户上传一张图片后,如果想再传一张图片,依然能够上传成功,并显示在页面上,尽管这样存储的是最后一次上传的图片,但是这样用户的使用体验感很差,这可不行丫!
第三幕
该怎么办呢?这必须要把存储图片文件做一个限制丫~ 翻开elementUI开发文档后,发现了limit这个组件参数
于是添加关键字limit=“1”,对图片上传进行了限制
可是这样问题真的解决了嘛?
第四幕
答案是否定的,虽然但是,这样并不能解决问题。于是拿出了必杀技
uploadMiniChange (file, fileList) {
if (fileList.length > 1) {
fileList.splice(0, 1)
}
}
终于,this bug 被KO~~.