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

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

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

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

目录

前言

一、项目介绍

1.开发环境

2.功能

3.项目运行截图

二、前端实现

1.引入库

2.编写Vue组件

3.运行前端工程

小结


前言

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

一、项目介绍

项目下载

gitee:https://gitee.com/wusupweilgy/springboot-vue.git(点个star呀😎)

1.开发环境

前端:vue2+element-ui组件

后端:springboot

2.功能

  1. 多图片的上传

  2. 前端展示图片

3.项目运行截图


 


 


二、前端实现

1.引入库

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

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

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官网

<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的路由器。添加以下内容:

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.运行前端工程

npm run serve

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

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

小结

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

  • 9
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Spring Boot + Vue + ElementUI 的图片回显功能,需要以下步骤: 1. 在Vue中使用ElementUI的Upload组件上传图片,并将上传成功后的图片地址保存在Vue的data中。 2. 在Spring Boot的Controller中编写接收图片上传请求的方法,将上传的图片保存到服务器上,并返回图片的访问地址。 3. 在Vue中使用img标签展示上传成功的图片,将img标签的src属性设置为上传成功后返回的图片地址。 下面是一个简单的示例代码: Vue代码: ``` <template> <div> <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess" :show-file-list="false"> <el-button slot="trigger" size="small" type="primary">点击上传</el-button> </el-upload> <img v-if="imageUrl" :src="imageUrl" /> </div> </template> <script> export default { data() { return { imageUrl: '', uploadUrl: 'http://localhost:8080/upload' } }, methods: { handleUploadSuccess(response) { this.imageUrl = response.data.url; } } } </script> ``` Spring Boot代码: ``` @RestController public class UploadController { @PostMapping("/upload") public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) { try { // 保存上传的文件到服务器上 String fileName = file.getOriginalFilename(); String filePath = "path/to/save/" + fileName; File dest = new File(filePath); file.transferTo(dest); // 返回图片的访问地址 String imageUrl = "http://localhost:8080/images/" + fileName; return ResponseEntity.ok(imageUrl); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 注意:上述代码仅供参考,具体实现需要根据自己的需求进行适当的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java学长小李

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值