<template>
<!--
action:"后台上传图片的接口地址"
on-success:文件上传成功时的钩子
-->
<el-upload
ref="upload"
class="upload-demo"
action="http://118.178.243.81:9590/admin/v1/uploadImage"
:limit="1"
:on-exceed="handleExceed"
:auto-upload="false"
:on-success="imgUpSuccess"
>
<template #trigger>
<el-button type="primary">选择上传的文件</el-button>
</template>
<el-button class="ml-3" type="success" @click="submitUpload">
确定上传
</el-button>
<template #tip>
<div class="el-upload__tip text-red">
limit 1 file, new file will cover the old file
</div>
</template>
</el-upload>
<img
:src="Imagesrc"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const upload = ref<UploadInstance>()
let Imagesrc=ref('')
const handleExceed: UploadProps['onExceed'] = (files) => {
upload.value!.clearFiles()
const file = files[0] as UploadRawFile
file.uid = genFileId()
upload.value!.handleStart(file)
}
const submitUpload = () => {
upload.value!.submit()
}
//图片上传成功默认执行的钩子函数
const imgUpSuccess = (response: any) => {
console.log(response)
//获取接口回调数据(此处为需要拼接的图片地址)
Imagesrc.value="http://teststatic.yunhanenergy.com/upload"+response.data
console.log(Imagesrc)
};
</script>
vue3+elementplus实现图片上传和显示
于 2023-03-24 16:36:54 首次发布
该代码示例展示了如何在Vue应用中使用el-upload组件进行图片上传。用户选择文件后,会调用后台指定的接口(http://118.178.243.81:9590/admin/v1/uploadImage)进行上传,并在成功后更新图片源。限制一次只能上传一个文件,新文件会覆盖旧文件。
摘要由CSDN通过智能技术生成