Jelajahi Sumber

feat:添加Eai作业附件的文件上传接口

wuzilong 1 tahun lalu
induk
melakukan
1384abfba7

+ 125 - 0
seecoder-portal-server/src/main/java/cn/seecoder/seecoderportalserver/utility/EaiOssUtil.java

@@ -0,0 +1,125 @@
+package cn.seecoder.seecoderportalserver.utility;
+
+import cn.seecoder.seecoderportalserver.web.rest.errors.CustomErrorException;
+import com.aliyun.oss.HttpMethod;
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.aliyun.oss.model.GeneratePresignedUrlRequest;
+import com.aliyun.oss.model.OSSObjectSummary;
+import com.aliyun.oss.model.ObjectListing;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @author: Leonezhurui
+ * @Date: 2024/3/13 - 08:57
+ * @Package: EAI-Backend
+ */
+
+@Slf4j
+@Component
+public class EaiOssUtil {
+    @Value("${aliyun.oss-eai.bucketName}")
+    private String bucketName;
+
+    @Value("${aliyun.oss-eai.endpoint}")
+    private String endpoint;
+
+    @Value("${aliyun.oss-eai.accessKeyId}")
+    private String accessKeyId;
+
+    @Value("${aliyun.oss-eai.accessKeySecret}")
+    private String accessKeySecret;
+
+
+    // 上传文件
+    public String uploadFile(InputStream inputStream, String filePath) {;
+        OSS ossClient = getOss();
+        try {
+            ossClient.putObject(bucketName, filePath, inputStream);
+            // 默认情况下URL有效期是3600秒
+            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
+            URL url = ossClient.generatePresignedUrl(bucketName, filePath, expiration);
+            return url.toString();
+        } catch (Exception e) {
+//            log.error("服务器上传文件出错"+e.getMessage());
+            System.out.println("服务器上传文件出错"+e.getMessage());
+//            throw MyException.create(HttpStatus.INTERNAL_SERVER_ERROR, "服务器上传文件出错");
+            throw new CustomErrorException("服务器上传文件出错");
+        }
+    }
+
+    public String uploadEnduringFile(InputStream inputStream, String filePath) {
+        OSS ossClient = getOss();
+        try {
+            ossClient.putObject(bucketName, filePath, inputStream);
+            return "http://" + bucketName + "." + endpoint + "/" + filePath;
+        } catch (Exception e) {
+//            log.error("服务器上传文件出错" + e.getMessage());
+            System.out.println("服务器上传文件出错"+e.getMessage());
+//            throw MyException.create(HttpStatus.INTERNAL_SERVER_ERROR, "服务器上传文件出错");
+            throw new CustomErrorException("服务器上传文件出错");
+        }
+    }
+
+
+    /**
+     * 生成文件的预签名URL以供下载
+     * @param filePath 文件在OSS上的路径
+     * @param expirationTime 过期时间(单位:毫秒)
+     * @return 预签名URL
+     */
+    public String generatePresignedUrl(String filePath, long expirationTime) {
+        OSS ossClient = getOss();
+        // 设置URL过期时间
+        Date expiration = new Date(new Date().getTime() + expirationTime);
+        // 生成URL
+        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, filePath, HttpMethod.GET);
+        request.setExpiration(expiration);
+        URL url = ossClient.generatePresignedUrl(request);
+        return url.toString();
+    }
+
+    // 列出文件
+    public List<String> listFiles() {
+        OSS ossClient = getOss();
+        try {
+            List<String> fileNames = new ArrayList<>();
+            ObjectListing objectListing = ossClient.listObjects(bucketName);
+            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
+                fileNames.add(objectSummary.getKey());
+            }
+            return fileNames;
+        } catch (Exception e) {
+//            log.error("服务器获取文件列表错误:"+e.getMessage());
+            System.out.println("服务器获取文件列表错误"+e.getMessage());
+//            throw MyException.create(HttpStatus.INTERNAL_SERVER_ERROR, "服务器获取文件列表错误");
+            throw new CustomErrorException("服务器获取文件列表错误");
+        }
+    }
+
+    // 删除文件
+    public void deleteFile(String filePath) {
+        OSS ossClient = getOss();
+        try {
+            ossClient.deleteObject(bucketName, filePath);
+        } catch (Exception e) {
+//            log.error("服务器删除文件错误:"+e.getMessage());
+            System.out.println("服务器删除文件错误"+e.getMessage());
+//            throw MyException.create(HttpStatus.INTERNAL_SERVER_ERROR, "服务器删除文件错误");
+            throw new CustomErrorException("服务器删除文件错误");
+        }
+    }
+
+    private OSS getOss() {
+        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+    }
+
+}

+ 26 - 0
seecoder-portal-server/src/main/java/cn/seecoder/seecoderportalserver/utility/MyResponse.java

@@ -0,0 +1,26 @@
+package cn.seecoder.seecoderportalserver.utility;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * @author: Leonezhurui
+ * @Date: 2024/2/14 - 23:52
+ * @Package: EAI-Backend
+ */
+
+@Data
+@AllArgsConstructor
+public class MyResponse {
+    private int code;
+    private String msg;
+    private Object data;
+
+    public static MyResponse success(Object data) {
+        return new MyResponse(200, "Success", data);
+    }
+
+    public static MyResponse error(int errCode, String errMsg) {
+        return new MyResponse(errCode, errMsg, null);
+    }
+}

+ 63 - 0
seecoder-portal-server/src/main/java/cn/seecoder/seecoderportalserver/web/rest/EaiFileController.java

@@ -0,0 +1,63 @@
+package cn.seecoder.seecoderportalserver.web.rest;
+
+import cn.seecoder.seecoderportalserver.utility.EaiOssUtil;
+//import com.njuzr.eaibackend.utils.OssUtil;
+import cn.seecoder.seecoderportalserver.utility.MyResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author: Leonezhurui
+ * @Date: 2024/3/13 - 09:27
+ * @Package: EAI-Backend
+ */
+
+@Slf4j
+@RestController
+@RequestMapping("/api/eai/file")
+public class EaiFileController {
+    private final EaiOssUtil eaiOssUtil;
+
+    @Autowired
+    public EaiFileController(EaiOssUtil eaiOssUtil) {
+        this.eaiOssUtil = eaiOssUtil;
+    }
+
+
+    @PostMapping
+    public CompletableFuture<MyResponse> upload(@RequestParam("file") MultipartFile file) {
+        return CompletableFuture.supplyAsync(() -> {
+            try {
+                String filePath = "uploads/" + file.getOriginalFilename();
+                String url = eaiOssUtil.uploadFile(file.getInputStream(), filePath);
+//                log.info("url:" + url);
+                System.out.println("url:" + url);
+                return MyResponse.success(url);
+            } catch (IOException e) {
+                throw new RuntimeException("文件上传失败", e);
+            }
+        }).completeOnTimeout(
+                MyResponse.error(400,"文件上传超时,请稍后再试"),
+                300,  // 超时时间(秒)
+                TimeUnit.SECONDS
+        );
+    }
+
+    @GetMapping
+    public MyResponse getFiles() {
+        return MyResponse.success(eaiOssUtil.listFiles());
+    }
+
+    @DeleteMapping
+    public MyResponse delete(@RequestParam String filePath) {
+        eaiOssUtil.deleteFile(filePath);
+        return MyResponse.success("删除成功");
+    }
+
+}

+ 6 - 0
seecoder-portal-server/src/main/resources/application-dev.yml

@@ -22,3 +22,9 @@ aliyun:
     accessKeyId: LTAI4Fi1qmL4iuhH8t7G7r2H
     accessKeySecret: 7tJWyQqa0cMkQGaPMMvtH6c0VLiOO2
     bucketName: seec-portal
+
+  oss-eai:
+    endpoint: oss-cn-shanghai.aliyuncs.com
+    accessKeyId: LTAI5tAbkw8rkreiJbfcY1jZ
+    accessKeySecret: 2yvtVYE1qAZEgm0ChvdMqhp0LhB5Lj
+    bucketName: eai-files

+ 6 - 0
seecoder-portal-server/src/main/resources/application.yml

@@ -25,6 +25,12 @@ aliyun:
     accessKeySecret: 7tJWyQqa0cMkQGaPMMvtH6c0VLiOO2
     bucketName: seec-portal
 
+  oss-eai:
+    endpoint: oss-cn-shanghai.aliyuncs.com
+    accessKeyId: LTAI5tAbkw8rkreiJbfcY1jZ
+    accessKeySecret: 2yvtVYE1qAZEgm0ChvdMqhp0LhB5Lj
+    bucketName: eai-files
+
 spring:
   servlet:
     multipart: