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

news2024/9/27 12:26:59

目录

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.coloradmin.cn/o/1408221.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

微信小程序之全局配置-window和tabBar

学习的最大理由是想摆脱平庸&#xff0c;早一天就多一份人生的精彩&#xff1b;迟一天就多一天平庸的困扰。各位小伙伴&#xff0c;如果您&#xff1a; 想系统/深入学习某技术知识点… 一个人摸索学习很难坚持&#xff0c;想组团高效学习… 想写博客但无从下手&#xff0c;急需…

抖捧AI实景自动直播怎么玩

​在如今的全民直播时代&#xff0c;直播已经成为了众多实体店、品牌方所刚需的技能&#xff0c;但是大多数都不具备太多的直播能力 &#xff0c;这个时候实景自动直播就应运而生&#xff0c;但是很多人都没有想清楚&#xff0c;AI实景自动直播&#xff0c;到底适不适合自己用呢…

使用官方标定工具Dynamic Calibrator对RealSense D435i进行标定(二)

工具的安装教程可以看我的上一篇博文&#xff1a;Ubuntu 18.04安装Dynamic Calibration software for the Intel RealSense™ D400 Series Cameras&#xff08;一&#xff09; 使用教程参考user guide&#xff1a;https://www.intel.com/content/www/us/en/support/articles/0…

2023春秋杯冬季赛 --- Crypto wp

文章目录 前言Cryptonot_wiener 前言 比赛没打&#xff0c;赛后随便做一下题目 Crypto not_wiener task.py: from Crypto.Util.number import * from gmpy2 import * import random, os from hashlib import sha1 from random import randrange flagb x bytes_to_long(f…

IO 专题

使用try-with-resources语句块&#xff0c;可以自动关闭InputStream [实践总结] FileIUtils 共通方法最佳实践 [实践总结] java 获取在不同系统下的换行符 [实践总结] StreamIUtils 共通方法最佳实践 斜杠“/“和反斜杠“\“的区别 路径中“./”、“…/”、“/”代表的含义…

MySql索引事务讲解和(经典面试题)

&#x1f3a5; 个人主页&#xff1a;Dikz12&#x1f525;个人专栏&#xff1a;MySql&#x1f4d5;格言&#xff1a;那些在暗处执拗生长的花&#xff0c;终有一日会馥郁传香欢迎大家&#x1f44d;点赞✍评论⭐收藏 目录 索引 概念 索引的相关操作 索引内部数据结构 事务 为…

容联七陌x新飞电器|升级高效智能客服,实现满意度跃升新台阶

随着电商兴起&#xff0c;电器行业深入到各大电子商务平台&#xff0c;订单量、咨询量也随之增长&#xff0c;对及时响应、准确回答、高效解决、提高服务品质等需求逐渐增加。 新飞电器选择了与容联七陌合作企业版在线客服产品&#xff0c;共同打造高效、便捷、个性化的优质客…

达梦数据库增删改查常用操作及-2723: 仅当指定列列表,且SET IDENTITY_INSERT为ON时,才能对自增列赋值问题修复

创建表 CREATE TABLE DICT ( "ID" INT IDENTITY(1, 1) NOT NULL, "TYPE" VARCHAR(30), "CODE" BIGINT, "NAME" VARCHAR(300), "VALUE" VARCHAR(200), "DESCRIPTION" VARCHAR(255), "OPERATOR"…

【LeetCode力扣】面试题 17.14. 最小K个数(top-k问题)

目录 1、题目介绍 2、解题思路 2.1、优先队列解法 2.2、top-k问题解法 1、题目介绍 原题链接&#xff1a;面试题 17.14. 最小K个数 - 力扣&#xff08;LeetCode&#xff09; 题目要求非常简短&#xff0c;也非常简单&#xff0c;就是求一组数中的k个最小数。 2、解题思路 …

碳排放预测 | Matlab实现LSTM多输入单输出未来碳排放预测,预测新数据

碳排放预测 | Matlab实现LSTM多输入单输出未来碳排放预测&#xff0c;预测新数据 目录 碳排放预测 | Matlab实现LSTM多输入单输出未来碳排放预测&#xff0c;预测新数据预测效果基本描述程序设计参考资料 预测效果 基本描述 1.Matlab实现LSTM长短期记忆神经网络多输入单输出未来…

Tarjan 算法(超详细!!)

推荐在 cnblogs 上阅读 Tarjan 算法 前言 说来惭愧&#xff0c;这个模板仅是绿的算法至今我才学会。 我还记得去年 CSP2023 坐大巴路上拿着书背 Tarjan 的模板。虽然那年没有考连通分量类似的题目。 现在做题遇到了 Tarjan&#xff0c;那么&#xff0c;重学&#xff0c;开…

华为产业链之车载激光雷达

一、智能汽车 NOA 加快普及&#xff0c;L3 上路利好智能感知硬件 1、感知层是 ADAS 最重要的一环 先进驾驶辅助系统 &#xff08;ADAS&#xff0c; Advanced driver-assistance system&#xff09;分“感知层、决策层、执行层”三个层级&#xff0c;其中感知层是最重要的一环…

竞赛保研 车道线检测(自动驾驶 机器视觉)

0 前言 无人驾驶技术是机器学习为主的一门前沿领域&#xff0c;在无人驾驶领域中机器学习的各种算法随处可见&#xff0c;今天学长给大家介绍无人驾驶技术中的车道线检测。 1 车道线检测 在无人驾驶领域每一个任务都是相当复杂&#xff0c;看上去无从下手。那么面对这样极其…

算法题解析与总结(三)

5.4 如何高效解决接雨水问题 本文对应的力扣题目&#xff1a; 42.接雨水 说白了就是用一个数组表示一个条形图&#xff0c;问你这个条形图最多能接多少水&#xff0c;函数签名如下&#xff1a; int trap(int[] height);5.4.1 核心思路 暴力算法&#xff1a; int trap(vec…

递归算法

递归算法 概况步骤代码示例输出结果 概况 递归算法是一种通过在函数中调用自身来解决问题的方法。常用于解决需要重复执行相似操作的问题&#xff0c;例如树、图等数据结构的遍历&#xff0c;以及分治、动态规划等算法。 递归算法的基本思想是将大问题划分为一个或多个具有相…

编译原理2.3习题 语法制导分析[C++]

图源&#xff1a;文心一言 编译原理习题整理~&#x1f95d;&#x1f95d; 作为初学者的我&#xff0c;这些习题主要用于自我巩固。由于是自学&#xff0c;答案难免有误&#xff0c;非常欢迎各位小伙伴指正与讨论&#xff01;&#x1f44f;&#x1f4a1; 第1版&#xff1a;自…

帝国cms无限级分销的逻辑思路效果展示以及表结构的初步规划

#小李子9479# #帝国cms无限级分销# #帝国cms三级分销系统# 关于分销系统 &#xff0c;我们要解决以下几个重要的逻辑关系&#xff0c; 1&#xff0c;用户上下级关系&#xff0c;即A通过分享期邀请链接&#xff0c;B点击或扫码注册后&#xff0c;成为A的下线。 2。下级级别的…

从开发、部署到维护:SAAS与源代码小程序的全流程对比

在数字化时代&#xff0c;小程序已成为企业开展业务的重要工具。然而&#xff0c;小程序开发过程中存在多种形式&#xff0c;其中SAAS版本小程序和源代码小程序是最常见的两种。乔拓云SaaS系统作为业界领先的SaaS服务平台&#xff0c;为企业提供高效、便捷的小程序解决方案。与…

ctfshow反序列化(web254-web266)

目录 web254 web255 web256 web257 web258 web259 web260 web261 web262 web263 web264 web265 web266 web254 源码 <?php/* # -*- coding: utf-8 -*- # Author: h1xa # Date: 2020-12-02 17:44:47 # Last Modified by: h1xa # Last Modified time: 2020…

Vulnhub靶机:FunBox 5

一、介绍 运行环境&#xff1a;Virtualbox 攻击机&#xff1a;kali&#xff08;10.0.2.15&#xff09; 靶机&#xff1a;FunBox 5&#xff08;10.0.2.30&#xff09; 目标&#xff1a;获取靶机root权限和flag 靶机下载地址&#xff1a;https://www.vulnhub.com/entry/funb…