Browse Source

加入附件上传、预览、删除

wangliang 1 year ago
parent
commit
0ad33e5db2

+ 71 - 0
sop-business/src/main/java/com/qmth/sop/business/bean/dto/AttachmentInfoDto.java

@@ -0,0 +1,71 @@
+package com.qmth.sop.business.bean.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+/**
+ * @Description: 附件信息
+ * @Param:
+ * @return:
+ * @Author: wangliang
+ * @Date: 2023/7/31
+ */
+public class AttachmentInfoDto implements Serializable {
+
+    @ApiModelProperty(value = "文件名")
+    String fileName;
+
+    @ApiModelProperty(value = "文件格式")
+    String format;
+
+    @ApiModelProperty(value = "文件大小")
+    BigDecimal size;
+
+    @ApiModelProperty(value = "文件md5")
+    String md5;
+
+    public AttachmentInfoDto() {
+
+    }
+
+    public AttachmentInfoDto(String fileName, String format, BigDecimal size, String md5) {
+        this.fileName = fileName;
+        this.format = format;
+        this.size = size;
+        this.md5 = md5;
+    }
+
+    public String getFileName() {
+        return fileName;
+    }
+
+    public void setFileName(String fileName) {
+        this.fileName = fileName;
+    }
+
+    public String getFormat() {
+        return format;
+    }
+
+    public void setFormat(String format) {
+        this.format = format;
+    }
+
+    public BigDecimal getSize() {
+        return size;
+    }
+
+    public void setSize(BigDecimal size) {
+        this.size = size;
+    }
+
+    public String getMd5() {
+        return md5;
+    }
+
+    public void setMd5(String md5) {
+        this.md5 = md5;
+    }
+}

+ 88 - 0
sop-business/src/main/java/com/qmth/sop/business/bean/result/EditResult.java

@@ -0,0 +1,88 @@
+package com.qmth.sop.business.bean.result;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+/**
+ * @Description: 新增/更新返回值
+ * @Author: CaoZixuan
+ * @Date: 2021-03-22
+ */
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class EditResult implements Serializable {
+
+    @JsonSerialize(using = ToStringSerializer.class)
+    @ApiModelProperty(value = "主键")
+    private Long id;
+
+    @ApiModelProperty(value = "更新时间")
+    Long updateTime;
+
+    @ApiModelProperty(value = "成功状态")
+    Boolean success;
+
+    @ApiModelProperty(value = "附件url")
+    String url;
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public Boolean getSuccess() {
+        return success;
+    }
+
+    public void setSuccess(Boolean success) {
+        this.success = success;
+    }
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+
+    public Long getUpdateTime() {
+        if (Objects.isNull(updateTime)) {
+            return System.currentTimeMillis();
+        } else {
+            return updateTime;
+        }
+    }
+
+    public void setUpdateTime(Long updateTime) {
+        this.updateTime = updateTime;
+    }
+
+    public EditResult(Long id) {
+        this.id = id;
+    }
+
+    public EditResult(Boolean success) {
+        this.success = success;
+    }
+
+    public EditResult(Long id, String url) {
+        this.id = id;
+        this.url = url;
+    }
+
+    public EditResult(String url) {
+        this.url = url;
+    }
+
+    public EditResult() {
+    }
+}

+ 17 - 0
sop-business/src/main/java/com/qmth/sop/business/entity/BasicAttachment.java

@@ -2,7 +2,9 @@ package com.qmth.sop.business.entity;
 
 
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import com.qmth.sop.business.bean.dto.AttachmentInfoDto;
 import com.qmth.sop.common.base.BaseEntity;
 import com.qmth.sop.common.base.BaseEntity;
+import com.qmth.sop.common.contant.SystemConstant;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import io.swagger.annotations.ApiModelProperty;
 
 
@@ -45,6 +47,21 @@ public class BasicAttachment extends BaseEntity implements Serializable {
     @JsonSerialize(using = ToStringSerializer.class)
     @JsonSerialize(using = ToStringSerializer.class)
     private Long objId;
     private Long objId;
 
 
+    public BasicAttachment() {
+
+    }
+
+    public BasicAttachment(String path, AttachmentInfoDto attachmentInfoDto, Long createId) {
+        setId(SystemConstant.getDbUuid());
+        this.path = path;
+        this.name = attachmentInfoDto.getFileName();
+        this.type = attachmentInfoDto.getFormat();
+        this.size = attachmentInfoDto.getSize();
+        this.md5 = attachmentInfoDto.getMd5();
+        setCreateTime(System.currentTimeMillis());
+        setCreateId(createId);
+    }
+
     public Long getOrgId() {
     public Long getOrgId() {
         return orgId;
         return orgId;
     }
     }

+ 46 - 1
sop-business/src/main/java/com/qmth/sop/business/service/BasicAttachmentService.java

@@ -1,7 +1,9 @@
 package com.qmth.sop.business.service;
 package com.qmth.sop.business.service;
 
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.qmth.sop.business.bean.dto.AttachmentInfoDto;
 import com.qmth.sop.business.entity.BasicAttachment;
 import com.qmth.sop.business.entity.BasicAttachment;
+import com.qmth.sop.common.enums.UploadFileEnum;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.MultipartFile;
 
 
 import java.io.IOException;
 import java.io.IOException;
@@ -20,6 +22,49 @@ public interface BasicAttachmentService extends IService<BasicAttachment> {
      * 验证附件
      * 验证附件
      *
      *
      * @param file
      * @param file
+     * @return
+     * @throws IOException
      */
      */
-    public void validateAttachment(MultipartFile file) throws IOException;
+    public AttachmentInfoDto validateAttachment(MultipartFile file) throws IOException;
+
+    /**
+     * 上传文件接口
+     *
+     * @param file
+     * @param type
+     * @return
+     * @throws IOException
+     */
+    public BasicAttachment saveAttachment(MultipartFile file, UploadFileEnum type) throws Exception;
+
+    /**
+     * 删除附件
+     *
+     * @param basicAttachment
+     */
+    public void deleteAttachment(BasicAttachment basicAttachment) throws Exception;
+
+    /**
+     * 文件预览
+     *
+     * @param path
+     * @return
+     */
+    public String filePreview(String path) throws Exception;
+
+    /**
+     * 文件预览
+     *
+     * @param attachmentId
+     * @return
+     */
+    public String filePreview(Long attachmentId) throws Exception;
+
+    /**
+     * 文件预览
+     *
+     * @param basicAttachment
+     * @return
+     */
+    public String filePreview(BasicAttachment basicAttachment) throws Exception;
 }
 }

+ 104 - 5
sop-business/src/main/java/com/qmth/sop/business/service/impl/BasicAttachmentServiceImpl.java

@@ -1,26 +1,29 @@
 package com.qmth.sop.business.service.impl;
 package com.qmth.sop.business.service.impl;
 
 
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.qmth.sop.business.bean.dto.AttachmentInfoDto;
 import com.qmth.sop.business.cache.CommonCacheService;
 import com.qmth.sop.business.cache.CommonCacheService;
 import com.qmth.sop.business.entity.BasicAttachment;
 import com.qmth.sop.business.entity.BasicAttachment;
 import com.qmth.sop.business.entity.SysConfig;
 import com.qmth.sop.business.entity.SysConfig;
+import com.qmth.sop.business.entity.SysUser;
 import com.qmth.sop.business.mapper.BasicAttachmentMapper;
 import com.qmth.sop.business.mapper.BasicAttachmentMapper;
 import com.qmth.sop.business.service.BasicAttachmentService;
 import com.qmth.sop.business.service.BasicAttachmentService;
 import com.qmth.sop.common.contant.SystemConstant;
 import com.qmth.sop.common.contant.SystemConstant;
 import com.qmth.sop.common.enums.ExceptionResultEnum;
 import com.qmth.sop.common.enums.ExceptionResultEnum;
+import com.qmth.sop.common.enums.UploadFileEnum;
+import com.qmth.sop.common.util.FileStoreUtil;
 import com.qmth.sop.common.util.ServletUtil;
 import com.qmth.sop.common.util.ServletUtil;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.io.FilenameUtils;
 import org.apache.commons.io.FilenameUtils;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.MultipartFile;
 
 
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 import java.io.IOException;
 import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.BigDecimal;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
+import java.util.*;
 
 
 /**
 /**
  * <p>
  * <p>
@@ -36,13 +39,18 @@ public class BasicAttachmentServiceImpl extends ServiceImpl<BasicAttachmentMappe
     @Resource
     @Resource
     CommonCacheService commonCacheService;
     CommonCacheService commonCacheService;
 
 
+    @Resource
+    FileStoreUtil fileStoreUtil;
+
     /**
     /**
      * 验证附件
      * 验证附件
      *
      *
      * @param file
      * @param file
+     * @return
+     * @throws IOException
      */
      */
     @Override
     @Override
-    public void validateAttachment(MultipartFile file) throws IOException {
+    public AttachmentInfoDto validateAttachment(MultipartFile file) throws IOException {
         String fileName = FilenameUtils.getBaseName(file.getOriginalFilename());
         String fileName = FilenameUtils.getBaseName(file.getOriginalFilename());
         String format = "." + FilenameUtils.getExtension(file.getOriginalFilename());
         String format = "." + FilenameUtils.getExtension(file.getOriginalFilename());
 
 
@@ -79,5 +87,96 @@ public class BasicAttachmentServiceImpl extends ServiceImpl<BasicAttachmentMappe
         if (!Objects.equals(fileMd5, md5)) {
         if (!Objects.equals(fileMd5, md5)) {
             throw ExceptionResultEnum.MD5_EQUALS_FALSE.exception();
             throw ExceptionResultEnum.MD5_EQUALS_FALSE.exception();
         }
         }
+        return new AttachmentInfoDto(fileName, format, b, fileMd5);
+    }
+
+    /**
+     * 上传文件接口
+     *
+     * @param file
+     * @param type
+     * @return
+     * @throws IOException
+     */
+    @Override
+    @Transactional
+    public BasicAttachment saveAttachment(MultipartFile file, UploadFileEnum type) throws Exception {
+        BasicAttachment basicAttachment = null;
+        AttachmentInfoDto attachmentInfoDto = this.validateAttachment(file);
+        if (Objects.nonNull(attachmentInfoDto)) {
+            StringJoiner stringJoiner = SystemConstant.getDirName(type, true).add(file.getOriginalFilename());
+            JSONObject jsonObject = new JSONObject();
+            jsonObject.put(SystemConstant.TYPE, fileStoreUtil.uploadFileEnumIsOss(type) ? SystemConstant.OSS : SystemConstant.LOCAL);
+            fileStoreUtil.ossUpload(stringJoiner.toString(), file.getInputStream(), attachmentInfoDto.getMd5(), type.getFssType());
+            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
+            jsonObject.put(SystemConstant.UPLOAD_TYPE, type);
+            jsonObject.put(SystemConstant.PATH, stringJoiner.toString());
+            basicAttachment = new BasicAttachment(jsonObject.toJSONString(), attachmentInfoDto, sysUser.getId());
+            this.save(basicAttachment);
+        }
+        return basicAttachment;
+    }
+
+    /**
+     * 删除附件
+     *
+     * @param basicAttachment
+     */
+    @Override
+    public void deleteAttachment(BasicAttachment basicAttachment) throws Exception {
+        if (Objects.nonNull(basicAttachment) && Objects.nonNull(basicAttachment.getPath())) {
+            JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());
+            fileStoreUtil.ossDelete((String) jsonObject.get(SystemConstant.PATH), UploadFileEnum.valueOf((String) jsonObject.get(SystemConstant.UPLOAD_TYPE)).getFssType());
+        }
+    }
+
+    /**
+     * 文件预览
+     *
+     * @param path
+     * @return
+     */
+    @Override
+    public String filePreview(String path) throws Exception {
+        String url = null;
+        JSONObject jsonObject = JSONObject.parseObject(path);
+        UploadFileEnum uploadFileEnum = UploadFileEnum.valueOf((String) jsonObject.get(SystemConstant.UPLOAD_TYPE));
+        String attachmentType = (String) jsonObject.get(SystemConstant.TYPE);
+        String filePath = (String) jsonObject.get(SystemConstant.PATH);
+        if (Objects.equals(attachmentType, SystemConstant.LOCAL)) {
+            url = fileStoreUtil.getDictionaryConfig().fssPrivateDomain().getServer() + filePath;
+        } else {
+            if (uploadFileEnum == UploadFileEnum.UPLOAD) {
+                url = fileStoreUtil.getPrivateUrl(filePath, uploadFileEnum.getFssType());
+            } else {
+                url = fileStoreUtil.getDictionaryConfig().fssPublicDomain().getServer() + SystemConstant.ORG_SPLIT + filePath;
+            }
+        }
+        return url;
+    }
+
+    /**
+     * 文件预览
+     *
+     * @param attachmentId
+     * @return
+     */
+    @Override
+    public String filePreview(Long attachmentId) throws Exception {
+        BasicAttachment basicAttachment = this.getById(attachmentId);
+        Optional.ofNullable(basicAttachment).orElseThrow(() -> ExceptionResultEnum.ATTACHMENT_NO_DATA.exception());
+        return this.filePreview(basicAttachment.getPath());
+    }
+
+    /**
+     * 文件预览
+     *
+     * @param basicAttachment
+     * @return
+     * @throws Exception
+     */
+    @Override
+    public String filePreview(BasicAttachment basicAttachment) throws Exception {
+        return this.filePreview(basicAttachment.getPath());
     }
     }
 }
 }

+ 1 - 1
sop-business/src/main/resources/db/install/sop_db.sql

@@ -8,7 +8,7 @@ CREATE TABLE `basic_attachment` (
                                     `org_id` bigint DEFAULT NULL COMMENT '机构id',
                                     `org_id` bigint DEFAULT NULL COMMENT '机构id',
                                     `name` varchar(100) NOT NULL COMMENT '文件名',
                                     `name` varchar(100) NOT NULL COMMENT '文件名',
                                     `type` varchar(10) NOT NULL COMMENT '文件类型',
                                     `type` varchar(10) NOT NULL COMMENT '文件类型',
-                                    `size` int NOT NULL COMMENT '单位(KB)',
+                                    `size` DECIMAL(8, 2) NOT NULL COMMENT '单位(KB)',
                                     `md5` varchar(32) NOT NULL COMMENT '文件md5值',
                                     `md5` varchar(32) NOT NULL COMMENT '文件md5值',
                                     `path` varchar(2000) NOT NULL COMMENT '存储路径',
                                     `path` varchar(2000) NOT NULL COMMENT '存储路径',
                                     `create_id` bigint DEFAULT NULL COMMENT '创建人',
                                     `create_id` bigint DEFAULT NULL COMMENT '创建人',

+ 10 - 0
sop-common/src/main/java/com/qmth/sop/common/config/DictionaryConfig.java

@@ -16,12 +16,22 @@ import org.springframework.context.annotation.Configuration;
 @Configuration
 @Configuration
 public class DictionaryConfig {
 public class DictionaryConfig {
 
 
+    /**
+     * public fss
+     *
+     * @return
+     */
     @Bean
     @Bean
     @ConfigurationProperties(prefix = "com.qmth.fss.public", ignoreUnknownFields = false)
     @ConfigurationProperties(prefix = "com.qmth.fss.public", ignoreUnknownFields = false)
     public FssPublicDomain fssPublicDomain() {
     public FssPublicDomain fssPublicDomain() {
         return new FssPublicDomain();
         return new FssPublicDomain();
     }
     }
 
 
+    /**
+     * private fss
+     *
+     * @return
+     */
     @Bean
     @Bean
     @ConfigurationProperties(prefix = "com.qmth.fss.private", ignoreUnknownFields = false)
     @ConfigurationProperties(prefix = "com.qmth.fss.private", ignoreUnknownFields = false)
     public FssPrivateDomain fssPrivateDomain() {
     public FssPrivateDomain fssPrivateDomain() {

+ 65 - 0
sop-common/src/main/java/com/qmth/sop/common/contant/SystemConstant.java

@@ -2,9 +2,19 @@ package com.qmth.sop.common.contant;
 
 
 import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
 import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
 import com.qmth.boot.core.uid.service.UidService;
 import com.qmth.boot.core.uid.service.UidService;
+import com.qmth.sop.common.enums.ExceptionResultEnum;
+import com.qmth.sop.common.enums.UploadFileEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.util.LinkedMultiValueMap;
 import org.springframework.util.LinkedMultiValueMap;
 
 
+import java.io.File;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
 import java.nio.charset.Charset;
 import java.nio.charset.Charset;
+import java.time.LocalDateTime;
+import java.util.StringJoiner;
 
 
 /**
 /**
  * @Description: 系统常量
  * @Description: 系统常量
@@ -14,6 +24,7 @@ import java.nio.charset.Charset;
  * @Date: 2019/10/11
  * @Date: 2019/10/11
  */
  */
 public class SystemConstant {
 public class SystemConstant {
+    private final static Logger log = LoggerFactory.getLogger(SystemConstant.class);
 
 
     /**
     /**
      * 系统常量
      * 系统常量
@@ -49,6 +60,13 @@ public class SystemConstant {
     public static final String HYPHEN = "-";
     public static final String HYPHEN = "-";
     public static final String SYS_ADMIN = "sysadmin";
     public static final String SYS_ADMIN = "sysadmin";
     public static final String VERSION_VALUE = "1.0.0.1";
     public static final String VERSION_VALUE = "1.0.0.1";
+    public static final String DATE_TIME_FORMAT = "%02d";
+    public static final String PATH = "path";
+    public static final String TYPE = "type";
+    public static final String LOCAL = "local";
+    public static final String OSS = "oss";
+    public static final String UPLOAD_TYPE = "uploadType";
+    public static final String TEMP = "temp";
 
 
     /**
     /**
      * 系统配置
      * 系统配置
@@ -165,4 +183,51 @@ public class SystemConstant {
     public static String getNanoId() {
     public static String getNanoId() {
         return NanoIdUtils.randomNanoId();
         return NanoIdUtils.randomNanoId();
     }
     }
+
+    /**
+     * 获取dirname
+     *
+     * @param uploadFileEnum
+     * @param fileSpearator
+     * @return
+     */
+    public static StringJoiner getDirName(UploadFileEnum uploadFileEnum, boolean fileSpearator) {
+        LocalDateTime nowTime = LocalDateTime.now();
+        StringJoiner stringJoiner = new StringJoiner("");
+        stringJoiner.add(uploadFileEnum.getTitle()).add(File.separator)
+                .add(String.valueOf(nowTime.getYear())).add(File.separator)
+                .add(String.format(SystemConstant.DATE_TIME_FORMAT, nowTime.getMonthValue())).add(File.separator)
+                .add(String.format(SystemConstant.DATE_TIME_FORMAT, nowTime.getDayOfMonth()));
+        if (fileSpearator) {
+            stringJoiner.add(File.separator);
+        }
+        return stringJoiner;
+    }
+
+    /**
+     * 获取临时文件
+     *
+     * @param suffix
+     * @return
+     */
+    public static File getFileTempVar(String suffix) throws IOException {
+        File fileTmpDir = new File(System.getProperty(SystemConstant.TMP_DIR));
+        if (!fileTmpDir.exists()) {
+            fileTmpDir.mkdirs();
+        }
+        File file = File.createTempFile(SystemConstant.TEMP, suffix);
+        log.info("getFileTempVar_absolutePath:{}", file.getAbsolutePath());
+        return file;
+    }
+
+    /**
+     * URL 编码, Encode默认为UTF-8.
+     */
+    public static String urlEncode(String part) {
+        try {
+            return URLEncoder.encode(part, SystemConstant.CHARSET_NAME);
+        } catch (UnsupportedEncodingException e) {
+            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
+        }
+    }
 }
 }

+ 4 - 0
sop-common/src/main/java/com/qmth/sop/common/enums/ExceptionResultEnum.java

@@ -33,6 +33,10 @@ public enum ExceptionResultEnum {
     /**
     /**
      * 500
      * 500
      */
      */
+    ATTACHMENT_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 5000001, "上传文件失败"),
+
+    ATTACHMENT_NO_DATA(HttpStatus.INTERNAL_SERVER_ERROR, 5000002, "没有附件数据"),
+
     USER_NO_DATA(HttpStatus.INTERNAL_SERVER_ERROR, 5000009, "用户或密码不正确"),
     USER_NO_DATA(HttpStatus.INTERNAL_SERVER_ERROR, 5000009, "用户或密码不正确"),
 
 
     USER_ENABLE(HttpStatus.INTERNAL_SERVER_ERROR, 5000011, "用户已禁用"),
     USER_ENABLE(HttpStatus.INTERNAL_SERVER_ERROR, 5000011, "用户已禁用"),

+ 2 - 10
sop-common/src/main/java/com/qmth/sop/common/enums/UploadFileEnum.java

@@ -10,22 +10,14 @@ import java.util.Objects;
  * @Date: 2020/7/15
  * @Date: 2020/7/15
  */
  */
 public enum UploadFileEnum {
 public enum UploadFileEnum {
-    /**
-     * 客户端
-     */
-    PAPER("paper","private"),
     /**
     /**
      * 系统相关
      * 系统相关
      */
      */
-    UPLOAD("upload","private"),
+    UPLOAD("upload", "private"),
     /**
     /**
      * 导入导出
      * 导入导出
      */
      */
-    FILE("file","public"),
-
-    PDF("pdf","private"),
-
-    HTML("html","private");
+    FILE("file", "public");
 
 
     private String title;
     private String title;
     private String fssType;
     private String fssType;

+ 93 - 61
sop-common/src/main/java/com/qmth/sop/common/util/FileStoreUtil.java

@@ -1,7 +1,10 @@
 package com.qmth.sop.common.util;
 package com.qmth.sop.common.util;
 
 
 import com.qmth.boot.core.fss.service.FileService;
 import com.qmth.boot.core.fss.service.FileService;
+import com.qmth.boot.core.fss.store.FileStore;
 import com.qmth.sop.common.config.DictionaryConfig;
 import com.qmth.sop.common.config.DictionaryConfig;
+import com.qmth.sop.common.contant.SystemConstant;
+import com.qmth.sop.common.enums.ExceptionResultEnum;
 import com.qmth.sop.common.enums.UploadFileEnum;
 import com.qmth.sop.common.enums.UploadFileEnum;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FileUtils;
@@ -12,6 +15,8 @@ import org.springframework.stereotype.Component;
 
 
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 import java.io.*;
 import java.io.*;
+import java.time.Duration;
+import java.util.Objects;
 
 
 /**
 /**
  * @Description: 文件存储工具类
  * @Description: 文件存储工具类
@@ -28,6 +33,26 @@ public class FileStoreUtil {
     @Resource
     @Resource
     private DictionaryConfig dictionaryConfig;
     private DictionaryConfig dictionaryConfig;
 
 
+    public boolean uploadFileEnumIsOss(UploadFileEnum type) {
+        return type == UploadFileEnum.FILE ? this.publicIsOss() : this.privateIsOss();
+    }
+
+    public String uploadFileEnumConfig(UploadFileEnum type) {
+        return type == UploadFileEnum.FILE ? dictionaryConfig.fssPublicDomain().getConfig() : dictionaryConfig.fssPrivateDomain().getConfig();
+    }
+
+    public boolean privateIsOss(UploadFileEnum type) {
+        return Objects.nonNull(dictionaryConfig.fssPrivateDomain()) ? dictionaryConfig.fssPrivateDomain().getConfig().trim().startsWith("oss:") : false;
+    }
+
+    public boolean publicIsOss() {
+        return Objects.nonNull(dictionaryConfig.fssPublicDomain()) ? dictionaryConfig.fssPublicDomain().getConfig().trim().startsWith("oss:") : false;
+    }
+
+    public boolean privateIsOss() {
+        return Objects.nonNull(dictionaryConfig.fssPrivateDomain()) ? dictionaryConfig.fssPrivateDomain().getConfig().trim().startsWith("oss:") : false;
+    }
+
     /**
     /**
      * 上传文件
      * 上传文件
      *
      *
@@ -41,44 +66,6 @@ public class FileStoreUtil {
         log.info("dirName:{}", dirName);
         log.info("dirName:{}", dirName);
     }
     }
 
 
-//    /**
-//     * 上传文件到本地
-//     *
-//     * @param dirName     上传到地址
-//     * @param inputStream 流
-//     * @param catalogType 文件
-//     */
-//    public void localUpload(String dirName, InputStream inputStream, String md5, LocalCatalogEnum catalogType) throws Exception {
-//        log.info("ossUpload is come in");
-//        String configPath = "";
-//        switch (catalogType) {
-//            case LOCAL_FILE:
-//                configPath = dictionaryConfig.fssLocalFileDomain().getConfig();
-//                break;
-//            case LOCAL_PDF:
-//                configPath = dictionaryConfig.fssLocalPdfDomain().getConfig();
-//                break;
-//            default:
-//                break;
-//        }
-//        dirName = dirName.replaceAll(configPath, "");
-//        fileService.getFileStore(catalogType.getType()).write(dirName, inputStream, md5);
-//        log.info("dirName:{}", dirName);
-//    }
-
-//    /**
-//     * 上传文件到本地
-//     *
-//     * @param inputStream 流
-//     * @param finalFile   最终文件
-//     * @param catalogType 文件类型
-//     * @throws Exception 异常
-//     */
-//    public void copyInputStreamToFile(InputStream inputStream, File finalFile, String md5, LocalCatalogEnum catalogType) throws Exception {
-//        String dirName = finalFile.getPath().replaceAll("\\\\", "/");
-//        this.localUpload(dirName, inputStream, md5, catalogType);
-//    }
-
     /**
     /**
      * 上传文件
      * 上传文件
      *
      *
@@ -118,6 +105,20 @@ public class FileStoreUtil {
         return this.saveLocal(fileService.getFileStore(type).read(dirName), localPath);
         return this.saveLocal(fileService.getFileStore(type).read(dirName), localPath);
     }
     }
 
 
+    /**
+     * 从文件存储上下载文件到本地
+     *
+     * @param dirName   文件地址
+     * @param localFile 本地路径
+     * @param type      fileStore类型
+     * @throws Exception 异常
+     */
+    public File ossDownload(String dirName, File localFile, String type) throws Exception {
+        log.info("ossDownload is come in");
+        InputStream inputStream = fileService.getFileStore(type).read(dirName);
+        FileUtils.copyInputStreamToFile(inputStream, localFile);
+        return localFile;
+    }
 
 
     /**
     /**
      * 从文件存储上下载文件到byte[]
      * 从文件存储上下载文件到byte[]
@@ -132,18 +133,18 @@ public class FileStoreUtil {
     }
     }
 
 
     /**
     /**
-     * 从文件存储上下载文件到InputStream
+     * oss删除
      *
      *
-     * @param objectName 文件地址
-     * @param type       fileStore类型
-     * @throws Exception 异常
+     * @param objectName
+     * @param type
+     * @return
+     * @throws Exception
      */
      */
-    public InputStream ossDownloadIs(String objectName, String type) throws Exception {
-        log.info("oss Download is come in");
-        return fileService.getFileStore(type).read(objectName);
+    public boolean ossDelete(String objectName, String type) throws Exception {
+        log.info("oss delete is come in");
+        return fileService.getFileStore(type).delete(objectName);
     }
     }
 
 
-
     /**
     /**
      * 获取文件访问url
      * 获取文件访问url
      *
      *
@@ -153,20 +154,47 @@ public class FileStoreUtil {
      */
      */
     public String getPrivateUrl(String objectPath, String type) {
     public String getPrivateUrl(String objectPath, String type) {
         String server = null;
         String server = null;
-//        if ("public".equals(type)) {
-        server = dictionaryConfig.fssPublicDomain().getServer();
-        return server + File.separator + objectPath;
-//        } else if ("private".equals(type)) {
-//            Boolean oss = dictionaryConfig.sysDomain().isOss();
-//            if (Objects.nonNull(oss) && oss) {
-//                FileStore fileStore = fileService.getFileStore(type);
-//                return fileStore.getPresignedUrl(objectPath, Duration.ofMinutes(5L));
-//            } else {
-//                return dictionaryConfig.fssPrivateDomain().getServer() + "/" + objectPath;
-//            }
-//        } else {
-//            throw ExceptionResultEnum.ERROR.exception("文件存储store类型不存在");
-//        }
+        if ("public".equals(type)) {
+            server = dictionaryConfig.fssPublicDomain().getServer();
+            return server + SystemConstant.ORG_SPLIT + objectPath;
+        } else if ("private".equals(type)) {
+            if (this.privateIsOss()) {
+                FileStore fileStore = fileService.getFileStore(type);
+                return fileStore.getPresignedUrl(objectPath, Duration.ofMinutes(5L));
+            } else {
+                return dictionaryConfig.fssPrivateDomain().getServer() + objectPath;
+            }
+        } else {
+            throw ExceptionResultEnum.ERROR.exception("文件存储store类型不存在");
+        }
+    }
+
+    /**
+     * 获取文件访问url
+     *
+     * @param objectPath 文件路径
+     * @param type       文件上传的类型
+     * @return
+     */
+    public String getPrivateUrlExpire(String objectPath, String type, Boolean isExpire) {
+        String server = null;
+        if ("public".equals(type)) {
+            server = dictionaryConfig.fssPublicDomain().getServer();
+            return server + SystemConstant.ORG_SPLIT + objectPath;
+        } else if ("private".equals(type)) {
+            if (this.privateIsOss()) {
+                FileStore fileStore = fileService.getFileStore(type);
+                if (isExpire) {
+                    return fileStore.getPresignedUrl(objectPath, Duration.ofMinutes(5L));
+                } else {
+                    return fileStore.getPresignedUrl(objectPath, Duration.ofMinutes(300L));
+                }
+            } else {
+                return dictionaryConfig.fssPrivateDomain().getServer() + SystemConstant.ORG_SPLIT + objectPath;
+            }
+        } else {
+            throw ExceptionResultEnum.ERROR.exception("文件存储store类型不存在");
+        }
     }
     }
 
 
     /**
     /**
@@ -176,7 +204,7 @@ public class FileStoreUtil {
      * @return 类型
      * @return 类型
      */
      */
     public UploadFileEnum getUploadEnumByPath(String path) {
     public UploadFileEnum getUploadEnumByPath(String path) {
-        path = path.replaceAll("\\\\", "/");
+        path = path.replaceAll("\\\\", SystemConstant.ORG_SPLIT);
         String target = path.substring(0, path.indexOf('/'));
         String target = path.substring(0, path.indexOf('/'));
         return UploadFileEnum.valueOf(target.toUpperCase());
         return UploadFileEnum.valueOf(target.toUpperCase());
     }
     }
@@ -237,4 +265,8 @@ public class FileStoreUtil {
         }
         }
         return file;
         return file;
     }
     }
+
+    public DictionaryConfig getDictionaryConfig() {
+        return dictionaryConfig;
+    }
 }
 }

+ 36 - 23
sop-server/src/main/java/com/qmth/sop/server/api/SysController.java

@@ -4,26 +4,32 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.qmth.boot.api.annotation.Aac;
 import com.qmth.boot.api.annotation.Aac;
 import com.qmth.boot.api.annotation.BOOL;
 import com.qmth.boot.api.annotation.BOOL;
 import com.qmth.boot.api.constant.ApiConstant;
 import com.qmth.boot.api.constant.ApiConstant;
+import com.qmth.boot.api.exception.ApiException;
 import com.qmth.sop.business.bean.params.LoginParam;
 import com.qmth.sop.business.bean.params.LoginParam;
+import com.qmth.sop.business.bean.result.EditResult;
 import com.qmth.sop.business.bean.result.LoginResult;
 import com.qmth.sop.business.bean.result.LoginResult;
 import com.qmth.sop.business.cache.CommonCacheService;
 import com.qmth.sop.business.cache.CommonCacheService;
+import com.qmth.sop.business.entity.BasicAttachment;
 import com.qmth.sop.business.entity.SysConfig;
 import com.qmth.sop.business.entity.SysConfig;
 import com.qmth.sop.business.entity.SysUser;
 import com.qmth.sop.business.entity.SysUser;
+import com.qmth.sop.business.service.BasicAttachmentService;
 import com.qmth.sop.business.service.SysUserService;
 import com.qmth.sop.business.service.SysUserService;
 import com.qmth.sop.common.contant.SystemConstant;
 import com.qmth.sop.common.contant.SystemConstant;
 import com.qmth.sop.common.enums.AppSourceEnum;
 import com.qmth.sop.common.enums.AppSourceEnum;
 import com.qmth.sop.common.enums.ExceptionResultEnum;
 import com.qmth.sop.common.enums.ExceptionResultEnum;
 import com.qmth.sop.common.enums.LoginTypeEnum;
 import com.qmth.sop.common.enums.LoginTypeEnum;
+import com.qmth.sop.common.enums.UploadFileEnum;
 import com.qmth.sop.common.util.Result;
 import com.qmth.sop.common.util.Result;
 import com.qmth.sop.common.util.ResultUtil;
 import com.qmth.sop.common.util.ResultUtil;
 import com.qmth.sop.common.util.ServletUtil;
 import com.qmth.sop.common.util.ServletUtil;
 import io.swagger.annotations.*;
 import io.swagger.annotations.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;
 import org.springframework.util.CollectionUtils;
 import org.springframework.validation.BindingResult;
 import org.springframework.validation.BindingResult;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 import javax.validation.Valid;
 import javax.validation.Valid;
@@ -44,6 +50,7 @@ import java.util.Optional;
 @RestController
 @RestController
 @RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_COMMON)
 @RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_COMMON)
 public class SysController {
 public class SysController {
+    private final static Logger log = LoggerFactory.getLogger(SysController.class);
 
 
     @Resource
     @Resource
     SysUserService sysUserService;
     SysUserService sysUserService;
@@ -51,6 +58,9 @@ public class SysController {
     @Resource
     @Resource
     CommonCacheService commonCacheService;
     CommonCacheService commonCacheService;
 
 
+    @Resource
+    BasicAttachmentService basicAttachmentService;
+
     @ApiOperation(value = "登录")
     @ApiOperation(value = "登录")
     @RequestMapping(value = "/login", method = RequestMethod.POST)
     @RequestMapping(value = "/login", method = RequestMethod.POST)
     @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
     @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
@@ -113,24 +123,27 @@ public class SysController {
         return ResultUtil.ok(sysUserService.removeUserInfo(sysUser.getId(), false));
         return ResultUtil.ok(sysUserService.removeUserInfo(sysUser.getId(), false));
     }
     }
 
 
-    @ApiOperation(value = "测试1")
-    @RequestMapping(value = "/test1", method = RequestMethod.POST)
-    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
-    public Result test1() {
-        return ResultUtil.ok("测试1");
-    }
-
-    @ApiOperation(value = "测试2")
-    @RequestMapping(value = "/test2", method = RequestMethod.POST)
-    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
-    public Result test2() {
-        return ResultUtil.ok("测试2");
-    }
-
-    @ApiOperation(value = "测试3")
-    @RequestMapping(value = "/test3", method = RequestMethod.POST)
-    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
-    public Result test3() {
-        return ResultUtil.ok("测试3");
+    @ApiOperation(value = "文件上传接口")
+    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
+    @Transactional
+    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
+    public Result fileUpload(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
+                             @ApiParam(value = "上传文件类型", required = true) @RequestParam UploadFileEnum type) throws Exception {
+        BasicAttachment basicAttachment = null;
+        try {
+            basicAttachment = basicAttachmentService.saveAttachment(file, type);
+            Optional.ofNullable(basicAttachment).orElseThrow(() -> ExceptionResultEnum.ATTACHMENT_ERROR.exception());
+        } catch (Exception e) {
+            log.error(SystemConstant.LOG_ERROR, e);
+            if (Objects.nonNull(basicAttachment)) {
+                basicAttachmentService.deleteAttachment(basicAttachment);
+            }
+            if (e instanceof ApiException) {
+                ResultUtil.error((ApiException) e, e.getMessage());
+            } else {
+                ResultUtil.error(e.getMessage());
+            }
+        }
+        return ResultUtil.ok(new EditResult(basicAttachment.getId(), basicAttachmentService.filePreview(basicAttachment.getPath())));
     }
     }
 }
 }

+ 1 - 1
sop-server/src/main/resources/application.properties

@@ -53,7 +53,7 @@ spring.activiti.history-level=audit
 #com.qmth.fss.private.server=https://oss-file.qmth.com.cn/teachcloud-print-dev-private
 #com.qmth.fss.private.server=https://oss-file.qmth.com.cn/teachcloud-print-dev-private
 
 
 #com.qmth.fss.public.config=oss://LTAI4Fi8jVRYT49QBXU9x5QX:97aBLBfkQR5mzCiQa82yWLAH57eUd8@teachcloud-test.oss-cn-shenzhen.aliyuncs.com
 #com.qmth.fss.public.config=oss://LTAI4Fi8jVRYT49QBXU9x5QX:97aBLBfkQR5mzCiQa82yWLAH57eUd8@teachcloud-test.oss-cn-shenzhen.aliyuncs.com
-#com.qmth.fss.public.server=https://oss-cn-shenzhen.aliyuncs.com
+#com.qmth.fss.public.server=https://teachcloud-test.oss-cn-shenzhen.aliyuncs.com
 #com.qmth.fss.private.config=oss://LTAI4Fi8jVRYT49QBXU9x5QX:97aBLBfkQR5mzCiQa82yWLAH57eUd8@teachcloud-test.oss-cn-shenzhen.aliyuncs.com
 #com.qmth.fss.private.config=oss://LTAI4Fi8jVRYT49QBXU9x5QX:97aBLBfkQR5mzCiQa82yWLAH57eUd8@teachcloud-test.oss-cn-shenzhen.aliyuncs.com
 #com.qmth.fss.private.server=https://oss-cn-shenzhen.aliyuncs.com
 #com.qmth.fss.private.server=https://oss-cn-shenzhen.aliyuncs.com