1.需要實現的效果如下圖,在點擊提交的時候再提交file數據,和其他數據統一上傳,我把file轉換成了base64的格式,可以再上傳之前顯示縮略圖

2.代碼分析
action屬性值為"#"
增加了:http-request="httpRequest"方法
解釋:
http-request 覆蓋默認的上傳行為,可以自定義上傳的實現
<template>
<div>
<el-upload
class="avatar-uploader"
action="#"
:http-request="httpRequest"
:show-file-list="false"
:before-upload="beforeAvatarUpload">
<img v-if="data.imageUrl" :src="data.imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<div class="content">
<p>
<span>文章標題</span>
<el-input v-model="data.title" placeholder="文章標題"></el-input>
</p>
<p>
<span>文章簡介</span>
<el-input v-model="data.summary" placeholder="文章簡介"></el-input>
</p>
<p>
<span>文章內容</span>
<el-input v-model="data.content" placeholder="文章內容"></el-input>
</p>
<p>
<el-button type="primary" @click="onSubmit" class="submitButton">提交</el-button>
</p>
</div>
</div>
</template>
js相關代碼
httpRequest方法主要處理顯示縮略圖,並且將需要用到的file轉換成base64的文件格式
export default {
data () {
return {
data: {
title: '',
summary: '',
content: '',
imageUrl: ''
}
}
},
methods: {
// 上傳之前的格式設置
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上傳頭像圖片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!')
}
return isJPG && isLt2M
},
httpRequest (data) {
let _this = this
let rd = new FileReader() // 創建文件讀取對象
let file = data.file
rd.readAsDataURL(file) // 文件讀取裝換為base64類型
rd.onloadend = function (e) {
_this.data.imageUrl = this.result // this指向當前方法onloadend的作用域
}
},
onSubmit () {
console.log(this.data)
console.log('submit!')
}
}
}
</script>
