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"multipleaccept="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].namethis.price=res.data.data.list[0].price})},//图片上传成功之后:将上传图片的数据添加到fileListhandleSuccess(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 {@AutowiredUploadFileService 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 {@AutowiredUploadFileMapper uploadFileMapper;@Overridepublic 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>());}}@Overridepublic 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);}}@Overridepublic Result deleteGoodsImage(Goods goods) {goods.setImageUrl("");int count=uploadFileMapper.updateGoods(goods);if (count==1){return Result.succeed("删除成功");}else{return Result.failed("删除失败");}}@Overridepublic 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>whereid = #{id}</update></mapper>

4、upload相关参数 

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

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

相关文章

前端 防止浏览器提示记住密码以及自动填充密码

当前端 <input /> 的 type’password‘ 时&#xff0c;浏览器为了优化用户体验&#xff0c;会在表单提交后提示用户记住密码 如果不想要这样的行为&#xff0c;最简单的当然是提示用户自己在浏览器设置中进行相关配置 如果希望在代码层面阻止浏览器提示是否记住密码或者…

.git 文件夹结构解析

.git 文件夹结构解析 在这篇文章就让我们来看看这个 Git 仓库里的文件分别都是用来干什么的&#xff0c;以及在执行了相关的 Git 命令后这些文件会如何响应。 hooks&#xff08;钩&#xff09;&#xff1a;存放一些shell脚本info&#xff1a;存放仓库的一些信息logs&#xff…

ChromeDriver谷歌驱动最新版安装120/121/122

chromeDriver最新版本下载 最新驱动 https://googlechromelabs.github.io/chrome-for-testing/参考&#xff1a; https://blog.csdn.net/m0_57382185/article/details/134007615

ORM-02-Hibernate 对象关系映射(ORM)框架

拓展阅读 The jdbc pool for java.(java 手写 jdbc 数据库连接池实现) The simple mybatis.&#xff08;手写简易版 mybatis&#xff09; Hibernate Hibernate ORM 允许开发者更轻松地编写那些数据在应用程序进程结束后仍然存在的应用程序。 作为一个对象关系映射&#xff08…

基于蝗虫优化的KNN分类特征选择算法的matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.本算法原理 4.1 KNN分类器基本原理 4.2 特征选择的重要性 4.3 蝗虫优化算法&#xff08;GOA&#xff09; 5.完整程序 1.程序功能描述 基于蝗虫优化的KNN分类特征选择算法。使用蝗虫优化算法&#xff…

C++入门语法———命名空间,缺省参数,重载函数

文章目录 一.命名空间1.存在意义2.语法使用1.定义命名空间2.使用命名空间的三种方式 二.缺省参数1.全缺省参数2.半缺省参数 三.重载函数1.定义2.重载原理———名字修饰 一.命名空间 1.存在意义 C命名空间的主要意义是为了避免命名冲突&#xff0c;尤其是在大型项目中可能存在…

“高级SPA项目构建与路由实现“

目录 引言1. SPA项目构建1.1 安装vue-cli,webpack1.2 创建 Vue.js项目1.3 “一问一答”模式1.4 启动项目 2. SPA项目完成路由3. 基于SPA项目完成嵌套路由总结 引言 在现代Web开发中&#xff0c;单页应用&#xff08;SPA&#xff09;已经成为一种流行的开发模式。SPA通过在前端…

优优嗨聚:美团代运营服务,为商家赋能,打造流量转化的秘密武器

随着互联网的飞速发展&#xff0c;人们越来越依赖线上平台进行消费。作为国内领先的电商平台之一&#xff0c;美团吸引了众多商家入驻。然而&#xff0c;如何在竞争激烈的美团平台上脱颖而出&#xff0c;成为了商家们面临的一大挑战。此时&#xff0c;美团代运营服务应运而生&a…

HTML5和CSS3的新特性

HTML5的新特性主要是针对于以前的不足&#xff0c;增加了一些新的标签、新的表单和新的表单属性等 1&#xff0c;HTML5新增的语义化标签 <header> 头部标签 <nav> 导航标签 <article> …

《WebKit 技术内幕》学习之九(4): JavaScript引擎

4 实践——高效的JavaScript代码 4.1 编程方式 关于如何使用JavaScript语言来编写高效的代码&#xff0c;有很多铺天盖地的经验分享&#xff0c;以及很多特别好的建议&#xff0c;读者可以搜索相关的词条&#xff0c;就能获得一些你可能需要的结果。同时&#xff0c;本节希望…

记录centos安装nginx过程和问题

今天在centos上安装了nginx&#xff0c;遇到了些问题&#xff0c;记录一下。 使用yum直接安装的话安装的版本是1.20.1&#xff0c;使用源码包安装可以装到1.25.0&#xff08;最新稳定版&#xff09;。很有意思的一点是两种安装方法下安装的路径是不同的&#xff0c;且源码安装…

Java 面向对象案例 03(黑马)

代码&#xff1a; public class phoneTest {public static void main(String[] args) {phone [] arr new phone[3];phone p1 new phone("华为",6999,"白色");phone p2 new phone("vivo",4999,"蓝色");phone p3 new phone("苹…

手把手教你用深度学习做物体检测(一): 快速感受物体检测的酷炫

我们先来看看什么是物体检测&#xff0c;见下图&#xff1a; 如上图所示&#xff0c; 物体检测就是需要检测出图像中有哪些目标物体&#xff0c;并且框出其在图像中的位置。 本篇文章&#xff0c;我将会介绍如何利用训练好的物体检测模型来快速实现上图的效果&#xff0c;这里…

Pyside6中QTableWidget使用

目录 一&#xff1a;介绍&#xff1a; 二&#xff1a;演示 一&#xff1a;介绍&#xff1a; 在 PySide6 中&#xff0c;QTableWidget 是一个用于展示和编辑表格数据的控件。它提供了在窗口中创建和显示表格的功能&#xff0c;并允许用户通过单元格来编辑数据。 要使用 QTabl…

Windows 下 TFTP 服务搭建及 U-Boot 中使用 tftp 命令实现文件下载

目录 Tftpd32/64文件下载更多内容 TFTP&#xff08;Trivial File Transfer Protocol&#xff0c;简单文件传输协议&#xff09;是 TCP/IP 协议族中的一个用来在客户机与服务器之间进行简单文件传输的协议&#xff0c;提供不复杂、开销不大的文件传输服务&#xff0c;端口号为 6…

免费SSL申请和自动更新

当前是在mac下操作 安装certbot # mac下brew安装即可 brew install certbotcentos 安装 centos安装文档 申请泛解析证书 sudo certbot certonly --manual --preferred-challengesdns -d *.yourdomain.com## 输出 Saving debug log to /var/log/letsencrypt/letsencrypt.lo…

[Android] Android文件系统中存储的内容有哪些?

文章目录 前言root 文件系统/system 分区稳定性:安全性: /system/bin用来提供服务的二进制可执行文件:调试工具:UNIX 命令&#xff1a;调用 Dalvik 的脚本(upall script):/system/bin中封装的app_process脚本 厂商定制的二进制可执行文件: /system/xbin/system/lib[64]/system/…

6.php开发-个人博客项目Tp框架路由访问安全写法历史漏洞

目录 知识点 php框架——TP URL访问 Index.php-放在控制器目录下 ​编辑 Test.php--要继承一下 带参数的—————— 加入数据库代码 --不过滤 --自己写过滤 --手册&#xff08;官方&#xff09;的过滤 用TP框架找漏洞&#xff1a; 如何判断网站是thinkphp&#x…

nvm安装与使用教程

目录 nvm是什么 nvm安装 配置环境变量 更换淘宝镜像 安装node.js版本 nvm list available 显示可下载版本的部分列表 nvm install 版本号 ​编辑 nvm ls 查看已经安装的版本 ​编辑 nvm use 版本号(切换想使用的版本号) nvm是什么 nvm是node.js version management的…