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

发布时间:2024年01月22日

目录

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相关参数?

文章来源:https://blog.csdn.net/karlaofsky/article/details/135734718
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。