xiexiang 1 gadu atpakaļ
vecāks
revīzija
3ae92d9a87

+ 5 - 0
pom.xml

@@ -65,6 +65,11 @@
             <artifactId>pdfbox</artifactId>
             <version>2.0.4</version>
         </dependency>
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.10.2</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 4 - 0
src/main/java/com/example/fms/common/model/vo/ConfigSettingVO.java

@@ -17,4 +17,8 @@ public class ConfigSettingVO {
     private String userName;
     private String password;
     private String filePath;
+    private String endPoint;
+    private String accessKeyId;
+    private String accessKeySecret;
+    private String bucketName;
 }

+ 88 - 0
src/main/java/com/example/fms/service/File2OssService.java

@@ -0,0 +1,88 @@
+package com.example.fms.service;
+
+import com.example.fms.common.model.dto.DownloadSysFileDTO;
+import com.example.fms.common.model.dto.SystemFileDTO;
+import com.example.fms.common.model.vo.ConfigSettingVO;
+import com.example.fms.common.utils.FileUtils;
+import com.example.fms.exception.XiaoShiException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * OSS文件管理接口
+ * @Author xiexiang
+ * @Date 2024/4/1
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class File2OssService implements IFileFactory{
+    private final FileUtils fileUtils;
+
+    /**
+     * 上传文件
+     * @param files
+     * @param configSettingVO 根据传入的id,选择的配置类,选择的上传路径以及上传方法
+     * @return
+     * @throws IOException
+     */
+    public List<SystemFileDTO> uploadFile(List<MultipartFile> files, ConfigSettingVO configSettingVO) throws IOException {
+        List<SystemFileDTO> systemFileDTOS = new ArrayList<>();
+        for (MultipartFile file : files) {
+            try {
+                String directoryName = fileUtils.getDirectoryName();
+                SystemFileDTO systemFileDTO = OssService.upload(configSettingVO.getFilePath() + directoryName, file, configSettingVO);
+                //服务器存储目录位置(1.本地project/pas/prod/file 2.本地project/rms/prod/file 3.生产project/pas/prod/file 4.生产project/rms/prod/file)
+                systemFileDTO.setPType(configSettingVO.getId());
+                //FSS
+                systemFileDTO.setSourceId(configSettingVO.getSourceId());
+                systemFileDTO.setOriginalName(file.getOriginalFilename());
+                systemFileDTO.setFilePath(configSettingVO.getFilePath() + directoryName + "/" + systemFileDTO.getFileName());
+                systemFileDTOS.add(systemFileDTO);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        return systemFileDTOS;
+    }
+
+    @Override
+    public SystemFileDTO replaceFile(String fileGuid, MultipartFile file, ConfigSettingVO configSettingVO) {
+        return null;
+    }
+
+    /**
+     * 下载文件
+     * @param downloadSysFileDTO
+     * @param configSettingVO
+     * @return
+     */
+    public byte[] downloadFile(DownloadSysFileDTO downloadSysFileDTO, ConfigSettingVO configSettingVO) {
+        String filePath = downloadSysFileDTO.getFilePath();
+        try {
+            byte[] fileData = OssService.download(filePath, configSettingVO);
+            return fileData;
+        } catch (Exception e) {
+            throw new XiaoShiException("下载错误");
+        }
+    }
+
+    /**
+     * 删除文件
+     * @param filePath
+     * @param configSettingVO
+     */
+    public void deleteFile(String filePath, ConfigSettingVO configSettingVO) {
+        try {
+            OssService.delete(filePath, configSettingVO);
+        } catch (Exception e) {
+            throw new XiaoShiException("删除错误");
+        }
+    }
+}

+ 1 - 0
src/main/java/com/example/fms/service/File2SftpService.java

@@ -69,6 +69,7 @@ public class File2SftpService implements IFileFactory {
         }
         return systemFileDTO;
     }
+
     /**
      * 下载文件
      * @param downloadSysFileDTO

+ 3 - 0
src/main/java/com/example/fms/service/FileFactory.java

@@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
 @RequiredArgsConstructor
 public class FileFactory {
     private final File2SftpService file2SftpService;
+    private final File2OssService file2OssService;
 
     /**
      * 判断
@@ -24,6 +25,8 @@ public class FileFactory {
         switch(sourceName){
             case "FSS":
                 return file2SftpService;
+            case "OSS":
+                return file2OssService;
             default:
                 return null;
         }

+ 1 - 1
src/main/java/com/example/fms/service/FileMangerService.java

@@ -48,7 +48,7 @@ public class FileMangerService {
         if (files != null && files.size() != 0) {
             //1.调用解析配置方法,获取配置信息
             List<ConfigSettingVO> configSettingVOS = ExcuteConfigUtils.excuteConfigVO();
-            //2.根据传入id,获得配置类,根据配置类选择使用的上传方法
+            //2.根据传入id,获得配置类,根据配置类中的id去匹配sourceId来选择使用的上传方法
             ConfigSettingVO configSettingVO = configSettingVOS.stream().filter(item -> item.getId().equals(sourceId)).findFirst().orElse(null);
             //3.获取文件上传到服务器,调用工厂类
             String sourceName = configSettingVO.getSourceName();

+ 264 - 0
src/main/java/com/example/fms/service/OssService.java

@@ -0,0 +1,264 @@
+package com.example.fms.service;
+
+import cn.hutool.core.io.FileUtil;
+import cn.hutool.core.util.IdUtil;
+import com.aliyun.oss.ClientException;
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.aliyun.oss.OSSException;
+import com.aliyun.oss.model.*;
+import com.example.fms.common.model.dto.DownloadSysFileDTO;
+import com.example.fms.common.model.dto.SystemFileDTO;
+import com.example.fms.common.model.vo.ConfigSettingVO;
+import com.example.fms.common.utils.FileUtils;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * @Author xiexiang
+ * @Date 2024/3/29
+ */
+@RequiredArgsConstructor
+@Slf4j
+@Service
+public class OssService {
+
+    //创建桶
+    public void createBucket() throws Exception {
+        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
+        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
+        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
+        String accessKeyId = "LTAI5tGyG1Q7fKprgg1nWhXj";
+        String accessKeySecret = "Y6Erboh5lEFiRPR4XK8oCPMvUzYGLN";
+        // 填写Bucket名称。
+        String bucketName = "xiaoshi-pas";
+        // 填写资源组ID。如果不填写资源组ID,则创建的Bucket属于默认资源组。
+        //String rsId = "rg-aek27tc****";
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+        try {
+            // 创建CreateBucketRequest对象。
+            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
+
+            // 如果创建存储空间的同时需要指定存储类型、存储空间的读写权限、数据容灾类型, 请参考如下代码。
+            // 此处以设置存储空间的存储类型为标准存储为例介绍。
+            //createBucketRequest.setStorageClass(StorageClass.Standard);
+            // 数据容灾类型默认为本地冗余存储,即DataRedundancyType.LRS。如果需要设置数据容灾类型为同城冗余存储,请设置为DataRedundancyType.ZRS。
+            //createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
+            // 设置存储空间读写权限为公共读,默认为私有。
+            //createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
+
+            // 在支持资源组的地域创建Bucket时,您可以为Bucket配置资源组。
+            //createBucketRequest.setResourceGroupId(rsId);
+
+            // 创建存储空间。
+            ossClient.createBucket(createBucketRequest);
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message:" + oe.getErrorMessage());
+            System.out.println("Error Code:" + oe.getErrorCode());
+            System.out.println("Request ID:" + oe.getRequestId());
+            System.out.println("Host ID:" + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message:" + ce.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+    }
+
+
+
+    public void deleteBucket() throws Exception {
+        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
+        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
+        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
+        String accessKeyId = "LTAI5tGyG1Q7fKprgg1nWhXj";
+        String accessKeySecret = "Y6Erboh5lEFiRPR4XK8oCPMvUzYGLN";
+        // 填写Bucket名称。
+        String bucketName = "xiaoshi-pas";
+
+
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+        try {
+            // 删除存储空间。
+            ossClient.deleteBucket(bucketName);
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message:" + oe.getErrorMessage());
+            System.out.println("Error Code:" + oe.getErrorCode());
+            System.out.println("Request ID:" + oe.getRequestId());
+            System.out.println("Host ID:" + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message:" + ce.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+    }
+
+
+    /**
+     * OSS下载文件
+     * @param filePath
+     * @param configSettingVO
+     * @return
+     * @throws Exception
+     */
+    public static byte[] download(String filePath, ConfigSettingVO configSettingVO) throws Exception {
+        String endpoint = configSettingVO.getEndPoint();
+        String accessKeyId = configSettingVO.getAccessKeyId();
+        String accessKeySecret = configSettingVO.getAccessKeySecret();
+        String bucketName = configSettingVO.getBucketName();
+        String objectName = filePath;
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        try {
+            // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
+            OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
+            //读取文件内容
+
+            byte[] buffer = new byte[1024];
+            int len;
+            while ((len = ossObject.getObjectContent().read(buffer)) != -1) {
+                outputStream.write(buffer, 0 , len);
+            }
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message:" + oe.getErrorMessage());
+            System.out.println("Error Code:" + oe.getErrorCode());
+            System.out.println("Request ID:" + oe.getRequestId());
+            System.out.println("Host ID:" + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message:" + ce.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+        return outputStream.toByteArray();
+    }
+
+    /**
+     * 删除文件
+     * @param filePath
+     * @param configSettingVO
+     * @throws Exception
+     */
+    public static void delete(String filePath, ConfigSettingVO configSettingVO) throws Exception {
+        String endpoint = configSettingVO.getEndPoint();
+        String accessKeyId = configSettingVO.getAccessKeyId();
+        String accessKeySecret = configSettingVO.getAccessKeySecret();
+        String bucketName = configSettingVO.getBucketName();
+        String objectName = filePath;
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        try {
+            // 删除文件或目录。如果要删除目录,目录必须为空。
+            ossClient.deleteObject(bucketName, objectName);
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message:" + oe.getErrorMessage());
+            System.out.println("Error Code:" + oe.getErrorCode());
+            System.out.println("Request ID:" + oe.getRequestId());
+            System.out.println("Host ID:" + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message:" + ce.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+    }
+
+    /**
+     * OSS上传文件
+     * @param directory
+     * @param multipartFile
+     * @param configSettingVO
+     * @return
+     * @throws IOException
+     */
+    public static SystemFileDTO upload(String directory, MultipartFile multipartFile, ConfigSettingVO configSettingVO) throws IOException {
+        SystemFileDTO systemFileDTO = new SystemFileDTO();
+        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
+        String endpoint = configSettingVO.getEndPoint();
+        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
+        String accessKeyId = configSettingVO.getAccessKeyId();
+        String accessKeySecret = configSettingVO.getAccessKeySecret();
+        // 填写Bucket名称,例如examplebucket。
+        String bucketName = configSettingVO.getBucketName();
+        // 随机生成文件名
+        String fileName = IdUtil.simpleUUID();
+        // 获取文件的后缀,不带“.”,必须是multipartFile类型
+        String extName = FileUtil.extName(multipartFile.getOriginalFilename());
+        //拼接文件完整名存入数据库表
+        String name = fileName + "." + extName;
+        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
+        String objectName = directory + "/" + name;
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        try {
+            // 创建PutObjectRequest对象。
+            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(multipartFile.getBytes()));
+            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
+            // ObjectMetadata metadata = new ObjectMetadata();
+            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
+            // metadata.setObjectAcl(CannedAccessControlList.Private);
+            // putObjectRequest.setMetadata(metadata);
+            // 上传。
+            PutObjectResult result = ossClient.putObject(putObjectRequest);
+            systemFileDTO.setFileName(name);
+            systemFileDTO.setFileLength(Long.toString(multipartFile.getSize()));
+            systemFileDTO.setIsDelete(0);
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message:" + oe.getErrorMessage());
+            System.out.println("Error Code:" + oe.getErrorCode());
+            System.out.println("Request ID:" + oe.getRequestId());
+            System.out.println("Host ID:" + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message:" + ce.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+        return systemFileDTO;
+    }
+
+}

+ 9 - 0
src/main/resources/configSetting.json

@@ -34,5 +34,14 @@
     "userName": "root",
     "passWord": "cslg-pas-820f1e412aaf",
     "filePath": "/project/rms/prod/file/"
+  },{
+    "sourceId": "2",
+    "sourceName": "OSS",
+    "id": 5,
+    "endPoint": "https://oss-cn-shanghai.aliyuncs.com",
+    "accessKeyId": "LTAI5tGyG1Q7fKprgg1nWhXj",
+    "accessKeySecret": "Y6Erboh5lEFiRPR4XK8oCPMvUzYGLN",
+    "bucketName": "xiaoshi-pas",
+    "filePath": "project/fms/prod/file/"
   }
 ]