html
<el-upload
ref="uploadRef"
class="avatar-uploader"
:action="''"
:auto-upload="false"
:limit="1"
:show-file-list="false"
:on-change="handleChange"
:on-exceed="handleExceed"
>
<el-button type="primary" plain>
<el-icon :size="20" class="m-r-2"><Files /></el-icon>
从本地上传图片
</el-button>
</el-upload>
<!--显示上传的图片-->
<div style="width: 600px;height: 400px;position: relative;">
<img :src="imageUrl" style="height: 400px;margin: 0 auto;">
</div>
<el-button :loading="tongueLoading" type="primary" size="default" @click="uploadPhoto">
<el-icon :size="20" class="m-r-2"><Upload /></el-icon>
上传图片
</el-button>
javascript
// 文件变化时触发
const handleChange = (file, fileList) => {
console.log('File change', file, fileList);
let { type, size } = file.raw
if (size > 1 * 1024 * 1024) {
ElMessage({
message: '文件大小不能超过1M',
type: 'warning'
})
return
}
let allowType = ['image/jpeg', 'image/png', 'image/jpg']
if (!allowType.includes(type)) {
ElMessage({
message: '请上传格式为jpg/png/jpeg格式的图片',
type: 'warning'
})
return
}
// 更新图片预览 URL
imageUrl.value = URL.createObjectURL(file.raw);
getBase64(file.raw)
tongueStep.value = 2;
};
const handleExceed: UploadProps['onExceed'] = (files) => {
uploadRef.value!.clearFiles()
const file = files[0] as UploadRawFile
file.uid = genFileId()
uploadRef.value!.handleStart(file)
}
let getBase64 = (file) => {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
let imgResult: any = ''
reader.readAsDataURL(file)
reader.onload = function () {
imgResult = reader.result
base64String.value = imgResult
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(imgResult)
}
})
}
// 发送上传
const uploadPhoto = async (type:string) => {
let imageStr = base64String.value.split('base64,')[1]
const formData = new FormData();
const data = {
image: imageStr
};
tongueLoading.value = true;
hasResult.value = false;
fetch('接口', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error)
});
};