上传图片并显示#Vue3#后端接口数据
效果:
上传并显示图片
代码:
<!-- 上传图片并显示 -->
<template>
<!-- 上传图片start -->
<div>
<el-form>
<el-form-item>
<el-upload
multiple
class="avatar-uploader"
action=""
:http-request="uploadFile1"
list-type="picture"
:show-file-list="false"
>
<img v-if="imageUrl" class="avatar" :src="imageUrl" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</el-form-item>
</el-form>
</div>
<!-- 上传图片end -->
</template>
<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import { ref } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
const router = useRouter();
console.log(router.currentRoute.value.path); //当前路由路径
sessionStorage.setItem("path", router.currentRoute.value.path);
// 定义表单
let tableForm = ref({
file: "",
});
const imageUrl = ref("");
// 上传并显示图片
const uploadFile1 = async (val: any) => {
tableForm.value.file = val.file;
console.log("tableForm", tableForm);
// 数据交互
let formdata = new FormData();
formdata.append("File", tableForm.value.file);
// 上传文件
await axios
.post("http://192.168.1.214:5050/api/File/UploadFile", formdata, {
headers: { "Content-Type": "multipart/form-data" },
})
.then((res) => {
console.log("res.data", res.data);
console.log("res.data.data.id", res.data.data.id);
// 找到文件路径
axios
.post("http://192.168.1.214:5050/api/File/FilePathInfo", {
id: res.data.data.id,
})
.then((result) => {
console.log("result.data.data.filePath", result.data.data.filePath);
let path = "http://192.168.1.214:5050" + result.data.data.filePath;
console.log("path", path);
imageUrl.value = path;
});
if (res.data.status === 200) {
ElNotification({
title: "上传成功",
message: "上传成功",
duration: 2000,
type: "success",
});
}
});
};
</script>
<style scoped lang="scss">
// 上传图片
.avatar-uploader .avatar {
width: 200px;
height: 200px;
display: block;
}
.avatar-uploader {
width: 200px;
height: 200px;
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.avatar-uploader:hover {
border-color: var(--el-color-primary);
}
.el-icon {
font-size: 20px;
color: #8c939d;
width: 200px;
height: 200px;
text-align: center;
}
</style>