默认已经安装好各种依赖,主要用到element-plus、axios。
通过Upload组件的http-request属性实现自定义图片上传请求功能。
代码实现:
通过自定义的uploadRequest方法,来实现图片上传和回显。
<template>
<el-form :model="editForm">
<el-form-item label="图片上传:">
<img :src="editForm.imageLink" class="imgBox">
<el-upload
:http-request="uploadRequest"
:limit="1"
v-model:file-list="fileList"
>
<el-button type="primary">上传图片</el-button>
</el-upload>
</el-form-item>
</el-form>
</template>
<script setup>
import axios from 'axios'
import {onMounted, reactive,ref} from 'vue'
//定义一个响应式数组用来接收图片
const fileList = ref([])
const editForm = reactive({
imageLink: '',
})
// 自定义图片方法
function uploadRequest(options){
const {file} = options;
let applyFile = new FormData();
applyFile.append('applyFile', file);
axios.post('http://localhost/api', applyFile,{
headers: {
"Content-Type": "multipart/form-data"
}
}).then(res=>{
editForm.imageLink = res.data.fileURL
// 上传成功获取回显值后要置空,否则二次上传会有问题
normalFileList.value = []
})
}
</script>
<style scoped>
.imgBox {
width: 30px;
height: 30px;
border-radius: 50%;
}
</style>