SpringBoot+Vue多图片上传和展示(一)

👨‍💻作者简介:全干的java博主

🎟️个人主页:无所谓^_^

ps:点赞是免费的,却可以让写博客的作者开心好几天😎


前言

在Web开发中,图片上传和展示是必不可少的功能之一。本文将介绍如何使用Spring Boot、Vue.js和ElementUI创建一个简单的图片上传和展示网站。

一、项目介绍

项目下载:

gitee:gitee.com/wusupweilgy...

1.开发环境

前端:vue2+element-ui组件

后端:springboot

2.功能

  1. 多图片的上传
  2. 前端展示图片

3.项目运行截图




二、前端实现

1.引入库

css 复制代码
npm install --save axios element-ui vue-router
  1. axios是一个HTTP客户端,可以用于向服务器发送请求。
  2. element-ui是ElementUI库,包含了丰富的UI组件,用于快速创建漂亮的用户界面。
  3. vue-router是Vue的路由器,用于管理应用程序的URL。

接下来,打开src/main.js文件,添加以下代码:

javascript 复制代码
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import axios from 'axios';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false

Vue.prototype.$axios = axios
axios.defaults.baseURL = "http://localhost:8088" //后端服务器访问地址

//注册插件
Vue.use(ElementUI)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

这个文件创建了一个axios实例,将其注入到Vue.js的原型中,以便Vue.js的组件可以轻松发送HTTP请求。此外,还配置了axios实例的基本URL。此外,还引入了ElementUI库,并使用Vue.use方法安装它的插件。

2.编写Vue组件

接下来,我们将创建一个Vue.js组件,用于上传和显示图片。在src/views目录下创建一个名为FileUpload.vue的文件,因为要使用element-ui的Upload上传组件,建议读者去官网查看这个组件如何使用,毕竟以后就是对着文档开发了,就当先熟悉熟悉。element-ui官网

xml 复制代码
<template>
    <div>
        <el-upload
                multiple
                :limit="3"
                class="file-box"
                ref="upload"
                action="http://localhost:8088/file"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :on-exceed="handleExceed"
                :file-list="images"
                list-type="picture"
                :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFile">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>
        <el-row :gutter="20">
            <el-col v-for="url in imageurls" :span="6">
                <el-image
                        style="width: 100px; height: 100px"
                        :src="url"
                        fit="fill"></el-image>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                images: [],
                imageurls: []
            };
        },
        methods: {
            submitFile() {
                if (this.images.length === 0) {
                    this.$message.warning("请选择文件")
                    return
                }
                let formData = new FormData() //创建一个表单
                this.images.forEach(file => {
                    formData.append("files", file.raw) //将文件传到表单中,files属性是后端接受的参数名
                })
                this.$axios.post(
                    '/file',
                    formData,
                    {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
                    this.$message.success("文件上传成功")
                    this.images = []
                    this.getImages()
                }).catch(error => {
                    this.$message.error("文件上传失败", error.msg)
                })
            },
            //移除文件列表时的钩子
            handleRemove(file, fileList) {
                this.images = fileList
                console.log("移除文件列表时的钩子", file);
            },
            //点击某个文件时的钩子
            handlePreview(file) {
                console.log("点击某个文件时的钩子", file);
            },
            //添加到上传列表时的钩子
            handleChange(file, fileList) {
                this.images = fileList
                console.log("添加到上传列表时的钩子", file)
            },
            //文件超出个数限制时的钩子
            handleExceed() {
                this.$message.warning("文件超出3个")
                console.log("文件超出个数限制时的钩子")
            },
            getImages() {
                this.$axios.get("/filelist")
                    .then(response => {
                        this.imageurls = response.data
                        console.log("获取图片列表成功")
                    })
                    .catch(error => {
                        this.$message.error("获取图片列表失败")
                    })
            }
        },
        created() {
            this.getImages()
        }
    }
</script>
<style scoped>

    .file-box {
        border: 1px solid #DCDFE6;
        width: 350px;
        margin: 50px auto;
        padding: 35px 35px 15px 35px;
        border-radius: 5px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        box-shadow: 0 0 25px #909399;
    }

    .el-row {
        margin-bottom: 20px;

    &
    :last-child {
        margin-bottom: 0;
    }

    }
    .el-col {
        border-radius: 4px;
    }

    .bg-purple-dark {
        background: #99a9bf;
    }

    .bg-purple {
        background: #d3dce6;
    }

    .bg-purple-light {
        background: #e5e9f2;
    }

    .grid-content {
        border-radius: 4px;
        margin-top: 10px;
        min-height: 36px;
    }

    .row-bg {
        padding: 10px 0;
        background-color: #f9fafc;
    }
</style>

这里我解释下el-upload标签里各个参数的作用

参数 说明
multiple 支持多选文件
list-type="picture" 文件列表的类型为图片
:auto-upload="false" 在选取文件后立即进行上传
:limit="3" 最大允许上传个数3
action="#" 必选参数,上传的地址
:on-remove="handleRemove" 文件列表移除文件时的钩子
:on-change="handleChange" 文件状态改变时的钩子
:on-exceed="handleExceed" 文件超出个数限制时的钩子
:on-preview="handlePreview" 点击文件列表中已上传的文件时的钩子
:file-list="images" 上传的文件列表

然后,创建名为index.js的新文件来配置Vue的路由器。添加以下内容:

javascript 复制代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import FileUpload from "@/views/FileUpload";
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: FileUpload
  },
]

const router = new VueRouter({
  routes
})

export default router

这是一个简单的路由配置,指定了名为FileUpload 的Vue.js组件为应用程序的根路径

3.运行前端工程

arduino 复制代码
npm run serve

现在,可以通过访问http://localhost:8080来访问图片上传的页面,但是因为后端接口还没写,所以不能请求。

下一篇:SpringBoot+Vue多图片上传和展示(二)

小结

本文介绍了如何使用Vue和ElementUI创建了一个简单的图片上传和展示页面。希望本文可以帮助你进一步学习和掌握这两个技术。如果这篇文章有幸帮助到你,希望读者大大们可以给作者给个三连呀😶‍🌫️😶‍🌫️😶‍🌫️

相关推荐
花花鱼9 小时前
Spring Security 与 Spring MVC
java·spring·mvc
言慢行善10 小时前
sqlserver模糊查询问题
java·数据库·sqlserver
专吃海绵宝宝菠萝屋的派大星10 小时前
使用Dify对接自己开发的mcp
java·服务器·前端
大数据新鸟10 小时前
操作系统之虚拟内存
java·服务器·网络
Tong Z10 小时前
常见的限流算法和实现原理
java·开发语言
凭君语未可10 小时前
Java 中的实现类是什么
java·开发语言
He少年10 小时前
【基础知识、Skill、Rules和MCP案例介绍】
java·前端·python
克里斯蒂亚诺更新10 小时前
myeclipse的pojie
java·ide·myeclipse
迷藏49411 小时前
**eBPF实战进阶:从零构建网络流量监控与过滤系统**在现代云原生架构中,**网络可观测性**和**安全隔离**已成为
java·网络·python·云原生·架构
迷藏49411 小时前
**发散创新:基于Solid协议的Web3.0去中心化身份认证系统实战解析**在Web3.
java·python·web3·去中心化·区块链