若依RuoYi前端分离版Vue中使用el-upload组件实现多图片上传功能(增加和修改)_若依上传多张图片存在一个字段里

<!--:action里面放图片上传调取的后台方法 :headers设置上传的请求头部,使请求携带自定义token,获取访问权限 -->
<!--:on-success图片上传成功后的回调方法,用于拿到图片存储路径等信息-->
<!--:before-upload图片上传前的逻辑判断,例如判断图片大小,格式等-->
<!--:on-preview图片预览方法 :on-remove图片删除方法   list-type代表文件列表的类型 -->
<!--file-list存放成功上传图片列表,这里此属性用于修改功能时页面已有图片的显示-->
<el-form-item prop="pictureUrl">
  <el-upload
	:action="imgUpload.url"
	:headers="imgUpload.headers"
	:on-success="handlePictureSuccess"
	:before-upload="beforePictureUpload"
	list-type="picture-card"
	:file-list="fileListShow"
	:on-preview="handlePictureCardPreview"
	:on-remove="handleRemove">
	<i class="el-icon-plus"></i>
  </el-upload>
  <!--图片预览的dialog-->
  <el-dialog :visible.sync="dialogVisible">
	<img width="100%" :src="dialogImageUrl">
  </el-dialog>
</el-form-item>

B.属性值方法的定义:

export default {
  name: "Forum",
  data() {
    return {
      //图片上传判断是否有相同图片
      isCommonName: true,
      //修改时此属性用于接收数据库中图片存储list,图片才能正常显示
      fileListShow: [],
      //页面上存的暂时图片地址List
      fileListPut: [],
      dialogImageUrl: '',
      dialogVisible: false,
      imgUpload: {
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 图片上传的方法地址:
          url: process.env.VUE_APP_BASE_API + "/forum/forum/multiPicturesUpload",
          url2: process.env.VUE_APP_BASE_API,
      }
    };
},
methods: {
    //图片上传前的相关判断
    beforePictureUpload(file){
      //每次进来初始化 isCommonName 为true
      this.isCommonName = true;
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      //判断是否有相同的图片,如何有即提示并添加失败
      if(this.fileListPut.length > 0){
        this.fileListPut.forEach((item,index)=>{
          if(item.name == file.name){
             this.$message.error('已存在相同的图片!');
             this.isCommonName = false;
          }
        })
      }
      if (!isJPG) {
        this.$message.error('请上传图片格式的文件!');
      }
      if (!isLt2M) {
        this.$message.error('上传的图片不能超过2MB!');
      }
      return isJPG && isLt2M && this.isCommonName;
    },
    //图片上传删除
    handleRemove(file, fileList) {
	  //根据传进来删除的file里图片,同时删除保存在fileListPut的相同图片
      if(this.fileListPut.length > 0){
          this.fileListPut = this.fileListPut.filter((item, index)=>{
          return item.name != file.name;
        })
      }
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file){
	  //设置图片访问路径
      const imgObjectUrl = this.videoUpload.url2 + file.response.imgUrl;
	  //这是每个成功上传图片,以对象的形式保存在一个数组中,进而以JSON格式保存在数据库中某个字段里
      let currentFile = {name: '',url: ''};
      currentFile.name = file.name;
      currentFile.url = imgObjectUrl;
	  //往此数组中保存当前图片对象
      this.fileListPut.push(currentFile);
    }
}

C.成功上传的图片访问路径以JSON格式保存在对应表的某个字符串类型的字段中,增加和修改方法中注意点如下:

1.增加提交事件中该字段JSON格式:this.form.pictureUrl = JSON.stringify(this.fileListPut);

2.修改事件中进行格式转化赋值:if(this.form.pictureUrl != ‘’){
                                                        this.fileListShow = JSON.parse(this.form.pictureUrl);
                                                        this.fileListPut = JSON.parse(this.form.pictureUrl);
                                                      }

D.效果图如下:

提示:表中保存的数据详情和格式(JSON格式数组)如下:

[{“name”:“蜡笔小新图1.jpg”,“url”:“/dev-api/profile/forum/2020/07/13/603569f501a64b7513af2097c3b44e93.jpg”},{“name”:“蜡笔小新图2.jpg”,“url”:“/dev-api/profile/forum/2020/07/13/8b9d14cec2b452246481c18cba21d029.jpg”},{“name”:“蜡笔小新图3.jpg”,“url”:“/dev-api/profile/forum/2020/07/13/e5ea7dc52a48281aa3b42ddf6372c68b.jpg”},{“name”:“蜡笔小新图4.jpg”,“url”:“/dev-api/profile/forum/2020/07/13/eb2b269756f901fdb78aeccc623e1c88.jpg”}]

三、后端上传图片方法代码:

/**
### Ruoyi 框架集成 Ueditor 富文本编辑器 #### 集成概述 为了在 Ruoyi 框架中成功集成并使用 UEditor 富文本编辑器,需完成几个关键配置步骤。这些步骤涉及引入必要的资源文件、初始化编辑器实例以及处理数据交互。 #### 准备工作 确保项目环境中已安装 Node.js npm 工具链,并通过 Maven 或 Gradle 添加所需依赖项来获取最新本的 UEditor 库[^1]。 #### 文件结构设置 创建一个新的模块用于承载 UEditor 的静态资源,在 `resources/static` 下新建名为 `ueditor` 的文件夹并将下载好的 UEditor 发布包解压至此处。该路径下应包含如下子目录: - jsp:放置与服务器端通信所需的 JSP 页面模板; - lang:多语言支持文件; - themes:主题样式表及相关图像素材; - third-party:第三方库集合; - ueditor.all.min.js 及其他核心脚本文件; ```bash ├── resources/ │ └── static/ │ ├── css/ │ ├── js/ │ └── ueditor/ │ ├── config.json │ ├── index.html │ ├── jsp/ │ ├── lang/ │ ├── themes/ │ └── ... ``` #### 修改配置文件 编辑位于 `src/main/resources/application.yml` 中的应用程序全局配置文件,添加以下内容以便于后续操作时指定上传图片存储位置等参数: ```yaml ruoyi: upload: path: ${user.home}/RuoYi/uploadPath # 设置默认保存路径 ``` #### 编写控制器类 编写一个简单的 RESTful API 控制器用来接收来自前端提交的数据流并将其持久化至磁盘上。此接口主要负责解析 multipart/form-data 类型请求体内的二进制对象进而调用工具函数完成实际存取动作。 ```java @RestController @RequestMapping("/api/ueditor") public class UeditorController { @PostMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Map<String, Object>> handleFileUpload(@RequestParam("upfile") MultipartFile file) { Map<String, Object> result = new HashMap<>(); try { String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename(); File dest = new File(System.getProperty("user.home"), "RuoYi/uploadPath/" + fileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); result.put("state", "SUCCESS"); result.put("url", "/static/uploadPath/" + fileName); // 返回相对 URL 地址供客户端访问 } catch (IOException e) { logger.error(e.getMessage(), e); result.put("state", "ERROR"); } return ResponseEntity.ok(result); } } ``` #### 初始化编辑器实例 最后一步是在页面加载完成后立即执行一段 JavaScript 脚本来启动 UEditor 实例并与后台服务建立连接关系。通常情况下会把这段代码嵌入到 HTML 文档底部附近的位置以减少阻塞渲染的风险。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Ruoyi Framework with UEditor</title> <!-- 引入UEditor --> <script type="text/javascript" src="/static/ueditor/ueditor.config.js"></script> <script type="text/javascript" src="/static/ueditor/ueditor.all.min.js"></script> <link rel="stylesheet" href="/static/ueditor/themes/default/css/ueditor.css"/> <style> /* 自定义样式 */ .ueditor-container { width: 90%; margin-left:auto; margin-right:auto;} </style> </head> <body> <div id="container" class="ueditor-container"></div> <script type="text/javascript"> // 创建编辑器实例 var ue = UE.getEditor('container', { serverUrl : '/api/ueditor/config', }); ue.ready(function(){ console.log('UEditor is ready'); }); </script> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值