問題描述:使用element-ui頭像上傳組件,不適用:action傳值,使用自己的上傳接口,傳值提示數據類型不是formdata格式?
<el-upload
class="avatar-uploader"
:action="''" // 沒有用就給個空的就行
:show-file-list="false"
:limit="1" // 限制傳一張
:auto-upload="false"
accept="image/jpeg,image/jpg,image/png"
:on-change="handleAvatarChange"
>
<img v-if="imgUrl" :src="imgUrl" class="avatar">
<el-button v-else><i class="avatar-uploader-icon" /> 上傳頭像</el-button>
<div slot="tip" class="el-upload__tip">建議尺寸200*200px,只能上傳jpg/png格式文件,文件不能超過200kb</div>
</el-upload>
接下來是方法:
handleAvatarChange(file) {
const isJPG = file.raw.type === 'image/jpeg'
const isPNG = file.raw.type === 'image/png'
const isLt2M = file.raw.size / 1024 / 1024 < 0.5
if (!isPNG && !isJPG) {
this.$message.error('上傳頭像圖片只能是 JPG/PNG 格式!')
return false
} else if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 200kb!')
return false
} else if (isLt2M && (isPNG || isJPG)) {
const formData = new FormData()
this.formData.url = file.raw
this.formData.name = file.name
for (const key in this.formData) {
formData.append(key, this.formData[key])
}
upload(formData) //調用上傳方法,傳遞FormData格式的參數
this.fileChange = false
return (isLt2M && (isPNG || isJPG))
}
好了,至此問題解決.