Vue+Element(el-upload+el-form的使用)+springboot

目录

1、编写模板

 2、发请求调接口

 3、后端返回数据

1.编写实体类

2.Controller类 

3、interface接口(Service层接口)

 4.Service(接口实现)

5、interface接口(Mapper层接口)

6、xml

4、upload相关参数 


 

 说明(该案例是一个el-form和el-upload结合的,逻辑是:需要先保存输入框的内容才能上传图片,分别调用了4(查询,删除、插入,上传图片)个接口)

1、编写模板

<template>
  <div class="container">
    <el-form ref="form" label-width="100px">
      <el-form-item label="商品名称:">
        <el-input v-model="name" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="商品价格:">
        <el-input v-model="price" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-button size="small" type="success" @click="saveGoods">保存</el-button>
    </el-form>

    <el-upload ref="upload"
               class="upload-demo"
               action="http://localhost:8080/api/upload/uploadImage"
               :disabled="isButtonDisabled"
               multiple
               accept="images/png"
               list-type="picture-card"
               drag
               :limit="10"
               :data="uploadData"
               :before-upload="beforeUpload"
               :on-progress="uploadProgress"
               :on-success="handleSuccess"
               :on-error="uploadError"
               :on-preview="handlePreview"
               :before-remove="beforeRemove"
               :on-remove="handleRemove"
               :on-exceed="handleExceed"
               :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2MB</div>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

 2、发请求调接口

<script>
export default {
    name: "uploadFile",
    data() {
        return {
            isButtonDisabled: true,
            name: '',
            price: '',
            uploadData: {
                id: ''
            },
            fileList: [
                { name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' },
                { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }
            ],
            dialogImageUrl: '',
            dialogVisible: false
        };
    },
    mounted() {
        const id = this.$route.params.id;
        this.selectById(id);
    },
    methods: {
        selectById(id){
            this.$axios({
                method:'post',
                url:'http://localhost:8080/api/upload/selectGoods',
                data:{
                    id:id
                }
            }).then((res)=>{
                //往fileList中添加一条数据,因为收的数据是[{}]所以需要获取索引list[0]
                this.fileList.push( {name: res.data.data.list[0].name, url: res.data.data.list[0].imageUrl})
                this.name=res.data.data.list[0].name
                this.price=res.data.data.list[0].price
            })
        },
        //图片上传成功之后:将上传图片的数据添加到fileList
        handleSuccess(response, file, fileList) {
            // 根据后端返回的数据修改fileList集合
            const { url, name } = response.data;
            const uploadedFile = {
                url,
                name,
                status: 'finished',
            };

            // 将上传的文件添加到fileList集合中
            fileList.push(uploadedFile);

            // 更新fileList,触发重新渲染
            this.$forceUpdate();
        },

        //上传失败的逻辑
        uploadError(err, file, fileList) {
            this.$message({
                message: err.message,
                type: "error",
            });
        },
        saveGoods() {
            if (this.name == '') {
                this.$message({
                    message: "请输入商品名称",
                    type: "error",
                });
                return;
            }
            if (this.price == '') {
                this.$message({
                    message: "请输入商品价格",
                    type: "error",
                });
                return;
            }
            this.$axios({
                method: 'post',
                url: "http://localhost:8080/api/upload/saveGoods",
                data: {
                    name: this.name,
                    price: this.price
                }
            }).then((res) => {
                this.$message({
                    message: "保存成功",
                    type: "success",
                });
                console.log("id:" + res.data.data);
                this.uploadData.id = res.data.data;

                this.isButtonDisabled = false; // 禁用上传按钮

            })

        },

        //点击上传成功之后的图片进行预览
        handlePreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        //上传之前调用:校验类型、大小
        beforeUpload(file) {
            if (this.uploadData.id == '') {
                this.$message({
                    message: "请先保存数据,再上传图片",
                    type: "error",
                });
                return false;
            }

            const fileSize = file.size / Math.pow(2, 20);
            if (file.type !== 'image/jpg' && file.type !== 'image/png') {
                this.$message.error('只能上传jpg/png文件')
                return false;
            }

            console.log("fileSieze:" + fileSize);
            if (fileSize > 2) {
                this.$message.error("图片不能超过2MB")
                return false;
            }

            return true;
        },

        //删除之前的逻辑
        beforeRemove(file, fileList) {
            return this.$confirm(`确定要删除图片 ${file.name}吗?`);
        },

        //删除的逻辑
        handleRemove(file, fileList) {
            if (this.uploadData.id !== '') {
                //发送请求,删除商品的图片
                this.$axios({
                    method: "post",
                    url: "http://localhost:8080/api/upload/deleteGoodsImage",
                    data: {
                        id: this.uploadData.id,

                    }
                }).then((res) => {
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                })

                // 根据删除的文件信息修改fileList集合
                const index = fileList.findIndex(item => item.name === file.name);
                if (index !== -1) {
                    fileList.splice(index, 1);
                }
                // 返回true允许删除,返回false阻止删除
                return true;
            }

        },

        //文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
        },

        //上传时,执行的逻辑
        uploadProgress(event, file, fileList) {

        }
    },

}
</script>

 3、后端返回数据

1.编写实体类
package com.example.goods_admin.entity;

public class Goods extends Page {
    private String id;
    private String name;
    private int price;
    private String imageUrl;
    private String status;

    public Goods() {
        super();
    }
    public Goods(int pageNum, int pageSize, String keyWord) {
        super(pageNum, pageSize, keyWord);
    }
    public Goods(int pageNum, int pageSize, String keyWord, String id, String name, int price, String imageUrl, String status) {
        super(pageNum, pageSize, keyWord);
        this.id = id;
        this.name = name;
        this.price = price;
        this.imageUrl = imageUrl;
        this.status = status;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
2.Controller类 

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @Autowired
    UploadFileService uploadFileService;

    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestPart MultipartFile[] file,@RequestParam("id") String id) {
        return uploadFileService.uploadImage(file,id);
    }
    @PostMapping("/saveGoods")
    public Result saveGoods(@RequestBody Goods goods) {
        return uploadFileService.saveGoods(goods);
    }

    @PostMapping("/deleteGoodsImage")
    public Result deleteGoodsImage(@RequestBody Goods goods) {
        return uploadFileService.deleteGoodsImage(goods);
    }

    @PostMapping("/selectGoods")
    public Result selectGoods(@RequestBody Goods goods) {
        return uploadFileService.selectGoods(goods);
    }


}
3、interface接口(Service层接口)
public interface UploadFileService {
    Result uploadImage(MultipartFile[] imageFile, String id);

    Result saveGoods(Goods goods);

    Result deleteGoodsImage(Goods goods);


    Result selectGoods(Goods goods);
}
 4.Service(接口实现)


@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Autowired
    UploadFileMapper uploadFileMapper;
    @Override
    public Result uploadImage(MultipartFile[] imageFile, String id) {

        //1、吧图片放到指定的文件夹下
        //2、更新数据


        try {
            // 指定目标文件夹路径
            String folderPath = "D:/imagePath/";

            // 获取文件名
            String fileName ="";

            // 遍历上传的文件数组
            for (MultipartFile file : imageFile) {
                // 获取文件名
                fileName = file.getOriginalFilename();

                // 构建目标文件路径
                Path targetPath = Paths.get(folderPath, fileName);

                // 将文件保存到目标文件夹
                Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            }
            Goods goods=new Goods();
            goods.setId(id);
            goods.setImageUrl(folderPath+fileName);
            uploadFileMapper.updateGoods(goods);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("name",fileName);
            resultMap.put("url",folderPath+fileName);

            // 文件保存成功,返回相应信息
            return Result.succeed("文件保存成功!",resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            // 文件保存失败,返回错误信息
            return  Result.failed ("文件保存失败!",new HashMap<String,Object>());
        }
    }

    @Override
    public Result saveGoods(Goods goods) {
        goods.setStatus("1");
        String id = UUID.randomUUID().toString();
        goods.setId(id);
        int count=uploadFileMapper.saveGoods(goods);
        if (count==1){
            return Result.succeed("保存成功",id);
        }else{
            return Result.failed("保存失败",id);
        }
    }

    @Override
    public Result deleteGoodsImage(Goods goods) {
        goods.setImageUrl("");
       int count=uploadFileMapper.updateGoods(goods);
        if (count==1){
            return Result.succeed("删除成功");
        }else{
            return Result.failed("删除失败");
        }
    }

    @Override
    public Result selectGoods(Goods goods) {
        int pageNum = goods.getPageNum()==0?1:goods.getPageNum();
        int pageSize = goods.getPageSize()==0?10:goods.getPageSize();

        //1、开启分页查询
        PageHelper.startPage(pageNum,pageSize);

        //2、查询结果
        List<Goods> goodsList  = uploadFileMapper.selectGoods(goods);

        //3、封装结果
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);

        //4、返回
        return Result.succeed("查询成功",goodsPageInfo);
    }



}
5、interface接口(Mapper层接口)
public interface UploadFileMapper {

    int saveGoods(Goods goods);
    int updateGoods(Goods goods);

    int deleteGoodsImage(Goods goods);


    List<Goods> selectGoods(Goods goods);
}
6、xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.goods_admin.mapper.UploadFileMapper">
    <resultMap id="BaseResultMap" type="com.example.goods_admin.entity.Goods">
        <id column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="price" jdbcType="INTEGER" property="price" />
        <result column="imageUrl" jdbcType="VARCHAR" property="imageUrl" />
        <result column="status" jdbcType="VARCHAR" property="status" />

    </resultMap>
    <insert id="saveGoods">
        INSERT INTO goods (
        <if test="id != null and id != ''">
            id
        </if>
        <if test="name != null and name != ''">
            ,name
        </if>
        <if test="price != null and price != ''">
            ,price
        </if>
        <if test="imageUrl != null and imageUrl != ''">
            ,imageUrl
        </if>
        <if test="status != null and status != ''">
            ,status
        </if>
        ) VALUES (
        <if test="id != null and id != ''">
            #{id}
        </if>
        <if test="name != null and name != ''">
            ,#{name}
        </if>
        <if test="price != null and price != ''">
            ,#{price}
        </if>
        <if test="imageUrl != null and imageUrl != ''">
            ,#{imageUrl}
        </if>
        <if test="status != null and status != ''">
            ,#{status}
        </if>
        )
    </insert>

    <delete id="deleteGoodsImage">
        delete from user
    <where>
        <if test="id!='' and id!=null">id = #{id}</if>
    </where>

    </delete>
    <select id="selectGoods" resultType="com.example.goods_admin.entity.Goods">
        select * from goods
        <where>
            <if test="keyWord !=null and keyWord!=''">
                name like concat('%', #{keyWord}, '%')
            </if>
            <if test="id !=null and id!=''">
                and id =#{id}
            </if>
        </where>
    </select>

    <update id="updateGoods">
       update goods
        <set>
            <if test="name!=''and name!=null">name=#{name},</if>
            <if test="price!=''and price!=null">price=#{price},</if>
            <if test="imageUrl!=null">imageUrl=#{imageUrl},</if>
            <if test="status!=''and status!=null">status=#{status}</if>
        </set>
        where
            id = #{id}
    </update>
    
</mapper>

4、upload相关参数 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/345732.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

别不信❗️你离数据专家只差一个CDMP证书

1⃣️为什么选择CDMP证书&#xff1f; &#x1f31f;&#x1f31f;亲爱的朋友们&#xff0c;如果你在寻找一个能让你在数据管理领域大展拳脚的证书&#xff0c;那么CDMP&#xff08;Certified Data Management Professional&#xff09;证书就是你的不二之选&#xff01;&#…

【数据结构】链表的分类和双向链表

本篇是基于上篇单链表所作&#xff0c;推荐与上篇配合阅读&#xff0c;效果更加 http://t.csdnimg.cn/UhXEj 1.链表的分类 链表的结构非常多样&#xff0c;以下情况组合起来就有8种&#xff08;2 x 2 x 2&#xff09;链表结构&#xff1a; 我们一般叫这个头为哨兵位 我们上回…

树,二叉树及其相关知识

1.树概念及结构 1.1树的概念 树是一种非线性的数据结构&#xff0c;它是由n&#xff08;n>0&#xff09;个有限结点组成一个具有层次关系的集合。把它叫做树是因 为它看起来像一棵倒挂的树&#xff0c;也就是说它是根朝上&#xff0c;而叶朝下的。 有一个特殊的结点&#…

搭建《幻兽帕鲁》服务器需要怎样配置的云服务器?

随着《幻兽帕鲁》这款游戏的日益流行&#xff0c;越来越多的玩家希望能够在自己的服务器上体验这款游戏。然而&#xff0c;搭建一个稳定、高效的游戏服务器需要仔细的规划和配置。本文将分享搭建《幻兽帕鲁》服务器所需的配置及搭建步骤&#xff0c;助力大家获得更加畅快的游戏…

【教学类-综合练习-09】20240105 大4班 综合材料(美术类:骰子、面具、AB手环)

背景需求 年终了&#xff0c;清理库存&#xff0c;各种打印的题型纸都拿出来&#xff0c;当个别化学习材料 教学过程&#xff1a; 时间&#xff1a;2024年1月2日下午 班级&#xff1a;大4班 人数&#xff1a;16人

微博处罚造谣账号只是”罚酒三杯“?

1月11日&#xff0c;一则#近视眼从800度降到100度的过程#话题登上微博热搜榜第一位。有博主称通过“视觉恢复的闪现技巧”可逐渐恢复视力。在9个小时时间内&#xff0c;该话题达到2.4亿阅读量&#xff0c;6.2万讨论量。 不过&#xff0c;遗憾的是&#xff0c;相关内容实际上是伪…

np.bincount函数的用法

官网写的非常清晰了&#xff0c; 返回数组的数量比x中的最大值大1&#xff0c;它给出了每个索引值在x中出现的次数。下面&#xff0c;我举个例子让大家更好的理解一下&#xff1a; np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1])最大值是7&a…

SQL提示与索引终章

✨博客主页&#xff1a;小小恶斯法克的博客 &#x1f388;该系列文章专栏&#xff1a;重拾MySQL-进阶篇 &#x1f4dc; 感谢大家的关注&#xff01; ❤️ 可以关注黑马IT&#xff0c;进行学习 目录 &#x1f680;SQL提示 &#x1f680;覆盖索引 &#x1f680;前缀索引 &…

Modelsim10.4安装

简介&#xff08;了解&#xff0c;可跳过&#xff09; modelsim是Mentor公司开发的优秀的HDL语言仿真软件。 它能提供友好的仿真环境&#xff0c;采用单内核支持VHDL和Verilog混合仿真的仿真器。它采用直接优化的编译技术、Tcl/Tk技术和单一内核仿真技术&#xff0c;编译仿真速…

基于springboot+vue的墙绘产品展示交易平台系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 研究背景…

MySQL建表练习

练习题目&#xff1a;通过所提供的E-R图和数据库模型图完成库表的创建&#xff0c;并插入适量的数据.要求必须使用SQL命令进行构建。 已知如下&#xff1a; 1、创建客户信息表&#xff1a; 代码&#xff1a; CREATE DATABASE Bank; //建库CREATE TABLE Userinfo(Cust…

aop介绍

AOP&#xff08;Aspect-Oriented Programming&#xff0c;面向方面编程&#xff09;&#xff0c;可以说是OOP&#xff08;Object-Oriented Programing&#xff0c;面向对象编程&#xff09;的补充和完善。OOP引入封装、继承和多态性等概念来建立一种对象层次结构&#xff0c;用…

ORBSLAM3安装

0. C11 or C0x Compiler sudo apt-get install gccsudo apt-get install gsudo apt-get install build-essentialsudo apt-get install cmake1. 依赖 在该目录终端。 1. 1.Pangolin git clone https://github.com/stevenlovegrove/Pangolin.git sudo apt install libglew-d…

Elasticsearch中的数值类型索引

Elasticsearch中的数值类型索引 | 你来啦 👩🏻‍💻 前言 最近杂七杂八的事情比较多,好久没更新文章了🤦‍♀️,今天就好好来理一理之前没搞清楚的关于ES数值索引的问题。ES主要是用于解决文本检索的场景,ES会默认将所有的输入内容当作字符串来理解,对于字段类型是…

leetcode刷题(剑指offer) 240.搜索二维矩阵Ⅱ

240.搜索二维矩阵Ⅱ 编写一个高效的算法来搜索 *m* x *n* 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性&#xff1a; 每行的元素从左到右升序排列。每列的元素从上到下升序排列。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,4,7,11,15],[2,5,8,12,19],[3,…

JAVA输入任意一个数字,实现递减求和(计算任意整数n的和)

摘要&#xff1a;本文介绍了使用Java编程语言计算任意整数n及其之前所有整数的和的示例代码。代码使用了Scanner类来读取用户输入的整数值&#xff0c;并通过循环计算出和结果并生成计算公式字符串。 内容&#xff1a; 在这个示例中&#xff0c;我们将展示如何使用Java编程语言…

《二叉树》——2

目录 前言&#xff1a; 树的节点个数&#xff1a; 树的叶子节点个数&#xff1a; 树的高度: 树的第K层节点个数&#xff1a; 二叉树查找值为x的节点: 二叉树的销毁&#xff1a; 总结&#xff1a; 前言&#xff1a; 我们在之前的blog中对于前中后的遍历有了深层次…

用JavaFX写了一个简易的管理系统

文章目录 前言正文一、最终效果1.1 主页面1.2 动物管理页面-初始化1.3 动物管理页面-修改&新增1.4 动物管理页面-删除&批量删除 二、核心代码展示2.1 启动类2.2 数据库配置-db.setting2.3 日志文本域组件2.4 自定义表格视图组件2.5 自定义分页组件2.6 动物管理页面2.7 …

Git教程学习:09 Git分支

文章目录 1 分支的简介2 分支的相关操作2.1 分支的创建2.2 分支的切换2.3 分支的合并2.4 分支推送到远程2.5 分支的删除2.6 分支的重命名 3 分支开发工作流程3.1 长期分支3.2 短期分支 1 分支的简介 几乎所有的版本控制系统都以某种形式支持分支。使用分支意味着我们可以把我们…

计算机硬件 6.1BIOS

第六章 计算机基本程序 第一节 BIOS与CMOS芯片 一、认识BIOS 1.中文含义&#xff1a;基本输入输出系统。 2.材质&#xff1a;ROM&#xff08;Flash Rom&#xff09; 3.地位&#xff1a;是操作系统与硬件之间的接口。 4.存放内容&#xff1a;①基本输入输出系统&#xff1b;…
最新文章