Przeglądaj źródła

添加图片上传功能,农业-农药管理-图片上传功能测试

吕宣芝 1 rok temu
rodzic
commit
fe86654a77

+ 220 - 0
data-ui/src/components/ImageUpload/dataUpload.vue

@@ -0,0 +1,220 @@
+<template>
+  <div class="component-upload-image">
+    <el-upload
+      multiple
+      :action="uploadImgUrl"
+      list-type="picture-card"
+      :on-success="handleUploadSuccess"
+      :before-upload="handleBeforeUpload"
+      :on-error="handleUploadError"
+      :on-exceed="handleExceed"
+      name="file"
+      :on-remove="handleRemove"
+      :show-file-list="true"
+      :headers="headers"
+      :file-list="fileList"
+      :on-preview="handlePictureCardPreview"
+      :class="{hide: this.fileList.length >= this.limit}"
+    >
+      <!--      :limit="limit"-->
+      <i class="el-icon-plus"></i>
+    </el-upload>
+
+    <!-- 上传提示 -->
+    <div class="el-upload__tip" slot="tip" v-if="showTip">
+      请上传
+      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
+      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
+      的文件
+    </div>
+
+    <el-dialog
+      :visible.sync="dialogVisible"
+      title="预览"
+      width="800"
+      append-to-body
+    >
+      <img
+        :src="dialogImageUrl"
+        style="display: block; max-width: 100%; margin: 0 auto"
+      />
+    </el-dialog>
+  </div>
+</template>
+
+<script>
+import { getToken } from "@/utils/auth";
+
+export default {
+  name: 'DataImageUpload',
+  props: {
+    ImageUpload: Function,
+    value: [String, Object, Array],
+    // 图片数量限制
+    // limit: {
+    //   type: Number,
+    //   default: 1,
+    // },
+    // 大小限制(MB)
+    fileSize: {
+      type: Number,
+      default: 10,
+    },
+    // 文件类型, 例如['png', 'jpg', 'jpeg']
+    fileType: {
+      type: Array,
+      default: () => ["png", "jpg", "jpeg"],
+    },
+    // 是否显示提示
+    isShowTip: {
+      type: Boolean,
+      default: true
+    }
+  },
+  data() {
+    return {
+      number: 0,
+      uploadList: [],
+      dialogImageUrl: "",
+      dialogName: "",
+      dialogVisible: false,
+      hideUpload: false,
+      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
+      headers: {
+        Authorization: "Bearer " + getToken(),
+      },
+      fileList: []
+    };
+  },
+  watch: {
+    value: {
+      handler(val) {
+        if (val) {
+          // 首先将值转为数组
+          const list = Array.isArray(val) ? val : this.value.split(',');
+          // 然后将数组转为对象数组
+          this.fileList = list.map(item => {
+            if (typeof item === "string") {
+              item = { name: item, url: item };
+            }
+            return item;
+          });
+        } else {
+          this.fileList = [];
+          return [];
+        }
+      },
+      deep: true,
+      immediate: true
+    }
+  },
+  computed: {
+    // 是否显示提示
+    showTip() {
+      return this.isShowTip && (this.fileType || this.fileSize);
+    },
+  },
+
+  methods: {
+    clear: function(){
+      alert('2')
+
+
+    },
+    // 删除图片
+    handleRemove(file, fileList) {
+      const findex = this.fileList.map(f => f.name).indexOf(file.name);
+      if(findex > -1) {
+        this.fileList.splice(findex, 1);
+        this.$emit("input", this.listToString(this.fileList));
+        // this.ImageUpload.setUrl("")
+      }
+    },
+    // 上传成功回调
+    handleUploadSuccess(res) {
+      this.uploadList.push({ name: res.data.url, url: res.data.webUrl });
+      if (this.uploadList.length === this.number) {
+        this.fileList = this.fileList.concat(this.uploadList);
+        this.uploadList = [];
+        this.number = 0;
+        // this.ImageUpload.setUrl(res.data.url)
+        this.$emit("input", this.listToString(this.fileList));
+        // this.$emit("input", JSON.stringify(this.fileList));
+        this.$modal.closeLoading();
+      }
+    },
+    // 上传前loading加载
+    handleBeforeUpload(file) {
+      let isImg = false;
+      if (this.fileType.length) {
+        let fileExtension = "";
+        if (file.name.lastIndexOf(".") > -1) {
+          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
+        }
+        isImg = this.fileType.some(type => {
+          if (file.type.indexOf(type) > -1) return true;
+          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
+          return false;
+        });
+      } else {
+        isImg = file.type.indexOf("image") > -1;
+      }
+
+      if (!isImg) {
+        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
+        return false;
+      }
+      if (this.fileSize) {
+        const isLt = file.size / 1024 / 1024 < this.fileSize;
+        if (!isLt) {
+          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
+          return false;
+        }
+      }
+      this.$modal.loading("正在上传图片,请稍候...");
+      this.number++;
+    },
+    // 文件个数超出
+    handleExceed() {
+      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
+    },
+    // 上传失败
+    handleUploadError() {
+      this.$modal.msgError("上传图片失败,请重试");
+      this.$modal.closeLoading();
+    },
+    // 预览
+    handlePictureCardPreview(file) {
+      this.dialogImageUrl = file.url;
+      this.dialogName = file.name;
+      this.dialogVisible = true;
+    },
+    // 对象转成指定字符串分隔
+    listToString(list, separator) {
+      let strs = "";
+      separator = separator || ",";
+      for (let i in list) {
+        strs += list[i].url + separator;
+      }
+      return strs != '' ? strs.substr(0, strs.length - 1) : '';
+    }
+  }
+};
+</script>
+<style scoped lang="scss">
+// .el-upload--picture-card 控制加号部分
+::v-deep.hide .el-upload--picture-card {
+  display: none;
+}
+// 去掉动画效果
+::v-deep .el-list-enter-active,
+::v-deep .el-list-leave-active {
+  transition: all 0s;
+}
+
+::v-deep .el-list-enter, .el-list-leave-active {
+  opacity: 0;
+  transform: translateY(0);
+}
+</style>
+

+ 12 - 1
data-ui/src/views/data/digitalagriculture/information/index.vue

@@ -116,6 +116,12 @@
         <el-form-item label="实际使用量(吨)" prop="realityUsage">
           <el-input v-model="form.realityUsage" placeholder="请输入实际使用量(吨)" maxlength="15"/>
         </el-form-item>
+        <el-col :span="24">
+          <el-form-item label="展示图片" prop="attachPaths">
+            <DataImageUpload ref="ImageUpload" :fileType="['png', 'jpg', 'jpeg']" :value="form.attachPaths"
+                         @input="getUrl"></DataImageUpload>
+          </el-form-item>
+        </el-col>
       </el-form>
       <div slot="footer" class="dialog-footer">
         <el-button type="primary" @click="submitForm">确 定</el-button>
@@ -139,11 +145,12 @@
   import { treeselect } from "@/api/system/dept";
   import Treeselect from '@riophae/vue-treeselect'
   import '@riophae/vue-treeselect/dist/vue-treeselect.css'
+  import DataImageUpload from "@/components/ImageUpload/dataUpload.vue";
 
   export default {
     name: "Information",
     dicts: ['sys_dept_type'],
-    components: {Treeselect, Deptselector},
+    components: {DataImageUpload, Treeselect, Deptselector},
     data() {
       return {
         // 部门名称
@@ -199,6 +206,10 @@
       this.getTreeselect();
     },
     methods: {
+      /** 上传 */
+      getUrl(url) {
+        this.form.attachPaths=url
+      },
       /** 查询部门下拉树结构 */
       getTreeselect() {
         treeselect().then(response => {

+ 7 - 0
src/main/java/com/sooka/sponest/data/digitalagriculture/domain/CenterdataTFarmPesticideInformation.java

@@ -8,6 +8,7 @@ import lombok.Data;
 
 import javax.validation.constraints.NotBlank;
 import javax.validation.constraints.NotNull;
+import java.util.List;
 
 /**
  * 农药信息对象 centerdata_t_farm_pesticide_information
@@ -68,4 +69,10 @@ public class CenterdataTFarmPesticideInformation extends BaseBusinessEntity {
     @Excel(name = "实际使用量" , suffix = "吨")
     private String realityUsage;
 
+    /**
+     * 图片上传
+     */
+    @ApiModelProperty(value = "图片上传", required = false)
+    private String attachPaths;
+
 }

+ 7 - 2
src/main/java/com/sooka/sponest/data/digitalagriculture/service/impl/CenterdataTFarmPesticideInformationServiceImpl.java

@@ -8,6 +8,8 @@ import com.sooka.sponest.data.base.service.impl.BaseServiceImpl;
 import com.sooka.sponest.data.digitalagriculture.domain.CenterdataTFarmPesticideInformation;
 import com.sooka.sponest.data.digitalagriculture.mapper.CenterdataTFarmPesticideInformationMapper;
 import com.sooka.sponest.data.digitalagriculture.service.ICenterdataTFarmPesticideInformationService;
+import com.sooka.sponest.data.system.attach.service.ICenterdataTAttachService;
+import com.sooka.sponest.data.utils.DataAttachUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
@@ -24,7 +26,6 @@ public class CenterdataTFarmPesticideInformationServiceImpl extends BaseServiceI
 
     @Autowired
     private CenterdataTFarmPesticideInformationMapper centerdataTFarmPesticideInformationMapper;
-
     /**
      * 查询农药信息列表
      *
@@ -46,7 +47,9 @@ public class CenterdataTFarmPesticideInformationServiceImpl extends BaseServiceI
      */
     @Override
     public CenterdataTFarmPesticideInformation selectCenterdataTFarmPesticideInformationById(String id) {
-        return centerdataTFarmPesticideInformationMapper.selectCenterdataTFarmPesticideInformationById(id);
+        CenterdataTFarmPesticideInformation centerdataTFarmPesticideInformation = centerdataTFarmPesticideInformationMapper.selectCenterdataTFarmPesticideInformationById(id);
+        centerdataTFarmPesticideInformation.setAttachPaths(DataAttachUtil.getDataAttachUpload(id));
+        return centerdataTFarmPesticideInformation;
     }
 
     /**
@@ -61,6 +64,7 @@ public class CenterdataTFarmPesticideInformationServiceImpl extends BaseServiceI
         centerdataTFarmPesticideInformation.setCreateBy(SecurityUtils.getUserId().toString());
         centerdataTFarmPesticideInformation.setCreateName(SecurityUtils.getLoginUser().getSysUser().getNickName());
         centerdataTFarmPesticideInformation.setCreateTime(DateUtils.getNowDate());
+        DataAttachUtil.dataAttachUpload(centerdataTFarmPesticideInformation.getId(),centerdataTFarmPesticideInformation.getAttachPaths(),"farm");
         return centerdataTFarmPesticideInformationMapper.insertCenterdataTFarmPesticideInformation(centerdataTFarmPesticideInformation);
     }
 
@@ -75,6 +79,7 @@ public class CenterdataTFarmPesticideInformationServiceImpl extends BaseServiceI
         centerdataTFarmPesticideInformation.setUpdateBy(SecurityUtils.getLoginUser().getUserid());
         centerdataTFarmPesticideInformation.setUpdateName(SecurityUtils.getLoginUser().getSysUser().getNickName());
         centerdataTFarmPesticideInformation.setUpdateTime(DateUtils.getNowDate());
+        DataAttachUtil.dataAttachUpload(centerdataTFarmPesticideInformation.getId(),centerdataTFarmPesticideInformation.getAttachPaths(),"farm");
         return centerdataTFarmPesticideInformationMapper.updateCenterdataTFarmPesticideInformation(centerdataTFarmPesticideInformation);
     }
 

+ 5 - 0
src/main/java/com/sooka/sponest/data/system/attach/mapper/CenterdataTAttachMapper.java

@@ -2,6 +2,7 @@ package com.sooka.sponest.data.system.attach.mapper;
 
 import com.sooka.sponest.data.system.attach.domain.AppDataTAttach;
 import com.sooka.sponest.data.system.attach.domain.CenterdataTAttach;
+import org.apache.ibatis.annotations.Param;
 
 import java.util.List;
 import java.util.Map;
@@ -79,4 +80,8 @@ public interface CenterdataTAttachMapper {
     int insertListCenterdataTAttach(List<CenterdataTAttach> list);
 
     List<Map<String, Object>> selectFailUpattah();
+
+    int deleteListCenterdataTAttach(@Param("busId") String busId,@Param("list") List<CenterdataTAttach> list);
+
+    List<String> selectDataAttachPathByBusId(String busId);
 }

+ 4 - 0
src/main/java/com/sooka/sponest/data/system/attach/service/ICenterdataTAttachService.java

@@ -66,4 +66,8 @@ public interface ICenterdataTAttachService {
     List<Map<String, Object>> selectFailUpattah();
 
     void updateEventAttachSchedule(Map<String, Object> paramMap,SysFile sysFile) throws Exception;
+
+    int deleteListCenterdataTAttach (String busId, List<CenterdataTAttach> list);
+
+    List<String> selectDataAttachPathByBusId (String busId);
 }

+ 11 - 0
src/main/java/com/sooka/sponest/data/system/attach/service/impl/CenterdataTAttachServiceImpl.java

@@ -162,4 +162,15 @@ public class CenterdataTAttachServiceImpl extends BaseServiceImpl implements ICe
     public List<Map<String, Object>> selectFailUpattah() {
         return centerdataTAttachMapper.selectFailUpattah();
     }
+
+    @Override
+    public int deleteListCenterdataTAttach(String busId, List<CenterdataTAttach> list) {
+        return centerdataTAttachMapper.deleteListCenterdataTAttach(busId, list);
+    }
+
+    @Override
+    public List<String> selectDataAttachPathByBusId(String busId) {
+        return centerdataTAttachMapper.selectDataAttachPathByBusId(busId);
+    }
+
 }

+ 96 - 0
src/main/java/com/sooka/sponest/data/utils/DataAttachUtil.java

@@ -0,0 +1,96 @@
+package com.sooka.sponest.data.utils;
+
+import com.ruoyi.common.core.utils.SpringUtils;
+import com.ruoyi.common.core.utils.StringUtils;
+import com.ruoyi.system.api.RemoteConfigService;
+import com.sooka.sponest.data.system.attach.domain.CenterdataTAttach;
+import com.sooka.sponest.data.system.attach.service.ICenterdataTAttachService;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+
+public class DataAttachUtil {
+
+    public static void dataAttachUpload(String busId, String newAttachPaths, String busIndx){
+        ICenterdataTAttachService bean = SpringUtils.getBean(ICenterdataTAttachService.class);
+        if (newAttachPaths != null){
+            String[] pathArray = newAttachPaths.split(",");
+            List<String> pathList = new ArrayList<>();
+            for (String path : pathArray) {
+                if (path.startsWith("http")) {
+                    if (path.contains("Download")) {
+                        int i1 = path.indexOf("group=");
+                        path = path.replace("&&path=", "/");
+                        path = path.substring(i1 + 6);
+                        pathList.add(path);
+                    } else {
+                        int i1 = path.indexOf('/');
+                        int i2 = path.indexOf('/', i1 + 1);
+                        int i3 = path.indexOf('/', i2 + 1);
+                        pathList.add(path.substring(i3 + 1));
+                    }
+                }
+            }
+
+            List<String> oldAttachList = bean.selectDataAttachPathByBusId(busId);
+
+            // 计算新增加的列表
+            List<String> addList = pathList.stream()
+                    .filter(id -> !oldAttachList.contains(id))
+                    .collect(Collectors.toList());
+            // 计算删除的列表
+            List<String> delList = oldAttachList.stream()
+                    .filter(id -> !pathList.contains(id))
+                    .collect(Collectors.toList());
+
+            // 批量添加附件地址
+            if (StringUtils.isNotEmpty(addList)){
+                List<CenterdataTAttach> attachList = toAttachList(busId, addList, busIndx);
+                bean.insertListCenterdataTAttach(attachList);
+            }
+            // 批量删除附件地址
+            if (StringUtils.isNotEmpty(delList)){
+                List<CenterdataTAttach> attachList = toAttachList(busId, delList, busIndx);
+                bean.deleteListCenterdataTAttach(busId,attachList);
+            }
+
+
+        }
+    }
+
+    private static List<CenterdataTAttach> toAttachList(String busId, List<String> addList, String busIndx) {
+        List<CenterdataTAttach> list = new ArrayList<>();
+        for (String addPath : addList){
+            CenterdataTAttach centerdataTAttach = new CenterdataTAttach();
+            centerdataTAttach.setBusId(busId);
+            centerdataTAttach.setAttachPath(addPath);
+            centerdataTAttach.setBusIndx(busIndx);
+            centerdataTAttach.setBusSource("PC");
+            centerdataTAttach.setFileName(null);
+            centerdataTAttach.setFileType("image");
+            list.add(centerdataTAttach);
+        }
+        return list;
+    }
+
+    public static String getDataAttachUpload(String busId){
+        ICenterdataTAttachService bean = SpringUtils.getBean(ICenterdataTAttachService.class);
+        List<String> list = bean.selectDataAttachPathByBusId(busId);
+        String fileUrl = SpringUtils.getBean(RemoteConfigService.class).remotegetConfigKey("fileUrl").getData();
+        String delimiter = ",";
+
+        StringBuilder sb = new StringBuilder();
+
+        for (String item : list) {
+            sb.append(fileUrl).append(item).append(delimiter);
+        }
+
+        // 移除最后一个逗号
+        if (sb.length() > 0) {
+            sb.deleteCharAt(sb.length() - 1);
+        }
+        return sb.toString();
+    }
+}

+ 11 - 0
src/main/resources/mapper/system/attach/CenterdataTAttachMapper.xml

@@ -176,4 +176,15 @@
         AND a.event_status_value IN ('forest_event_status_2','forest_event_status_5','forest_event_status_6','forest_event_status_7')
         order by a.create_time
     </select>
+
+    <delete id="deleteListCenterdataTAttach"  parameterType="CenterdataTAttach">
+        delete from centerdata_t_attach where bus_id = #{busId} and attach_path in
+        <foreach collection="list" item="item" index="index" open="(" separator="," close=")">
+            #{item.attachPath}
+        </foreach>
+    </delete>
+
+    <select id="selectDataAttachPathByBusId" resultType="String" parameterType="String">
+        select attach_path from centerdata_t_attach where bus_id = #{busId}
+    </select>
 </mapper>