Pārlūkot izejas kodu

fix: 上传修改

liaoyitao 3 mēneši atpakaļ
vecāks
revīzija
cf0f922a64

+ 22 - 0
pom.xml

@@ -154,6 +154,28 @@
154 154
             <version>1.37.0</version>
155 155
         </dependency>
156 156
 
157
+<!--        阿里云oss依赖-->
158
+        <dependency>
159
+            <groupId>com.aliyun.oss</groupId>
160
+            <artifactId>aliyun-sdk-oss</artifactId>
161
+            <version>3.17.4</version>
162
+        </dependency>
163
+        <dependency>
164
+            <groupId>javax.xml.bind</groupId>
165
+            <artifactId>jaxb-api</artifactId>
166
+            <version>2.3.1</version>
167
+        </dependency>
168
+        <dependency>
169
+            <groupId>javax.activation</groupId>
170
+            <artifactId>activation</artifactId>
171
+            <version>1.1.1</version>
172
+        </dependency>
173
+        <!-- no more than 2.3.3-->
174
+        <dependency>
175
+            <groupId>org.glassfish.jaxb</groupId>
176
+            <artifactId>jaxb-runtime</artifactId>
177
+            <version>2.3.3</version>
178
+        </dependency>
157 179
     </dependencies>
158 180
 
159 181
     <build>

+ 2 - 1
src/main/java/com/lqkj/link/config/OpenApiConfig.java

@@ -106,7 +106,8 @@ public class OpenApiConfig {
106 106
                         "/audit/v1/**",
107 107
                         "/notice/v1/**",
108 108
                         "/layer/v1/**",
109
-                        "/resource/v1/**")
109
+                        "/resource/v1/**",
110
+                        "/resource/ossUpload")
110 111
                 .build();
111 112
     }
112 113
 

+ 22 - 0
src/main/java/com/lqkj/link/config/ThreadPoolConfig.java

@@ -0,0 +1,22 @@
1
+package com.lqkj.link.config;
2
+
3
+import org.springframework.context.annotation.Bean;
4
+import org.springframework.context.annotation.Configuration;
5
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
6
+
7
+import java.util.concurrent.Executor;
8
+
9
+@Configuration
10
+public class ThreadPoolConfig {
11
+
12
+    @Bean(name = "taskExecutor")
13
+    public Executor taskExecutor() {
14
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
15
+        executor.setCorePoolSize(10); // 核心线程池大小
16
+        executor.setMaxPoolSize(20); // 最大线程池大小
17
+        executor.setQueueCapacity(50); // 队列容量
18
+        executor.setThreadNamePrefix("Async-"); // 线程名称前缀
19
+        executor.initialize();
20
+        return executor;
21
+    }
22
+}

+ 13 - 0
src/main/java/com/lqkj/link/module/base/service/BaseService.java

@@ -1,15 +1,20 @@
1 1
 package com.lqkj.link.module.base.service;
2 2
 
3 3
 import com.lqkj.link.message.MessageBean;
4
+import com.lqkj.link.util.AliOSSUtils;
4 5
 import com.lqkj.link.util.FileUtils;
6
+import org.springframework.beans.factory.annotation.Autowired;
5 7
 import org.springframework.stereotype.Service;
6 8
 import org.springframework.web.multipart.MultipartFile;
7 9
 
10
+import java.io.IOException;
8 11
 import java.util.UUID;
9 12
 
10 13
 @Service
11 14
 public class BaseService {
12 15
 
16
+    @Autowired
17
+    private AliOSSUtils aliOSSUtils;
13 18
     public MessageBean<String> uploadImg(MultipartFile file, String path) {
14 19
         String fileName = file.getOriginalFilename();
15 20
         String suffix = fileName == null ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
@@ -75,4 +80,12 @@ public class BaseService {
75 80
         FileUtils.saveFile(file, filePath, newFileName);
76 81
         return MessageBean.ok(filePath.substring(1) + newFileName, "上传模型文件");
77 82
     }
83
+
84
+    public String ossUpload(MultipartFile file) {
85
+        try {
86
+            return aliOSSUtils.upload(file);
87
+        } catch (IOException e) {
88
+            throw new RuntimeException(e);
89
+        }
90
+    }
78 91
 }

+ 13 - 0
src/main/java/com/lqkj/link/module/zone/controller/ResourceController.java

@@ -236,4 +236,17 @@ public class ResourceController {
236 236
         String userCode = jwtService.decryptUsernameWithHeader(authHeader);
237 237
         return MessageBean.ok(resourceService.needRefreshResource(userCode), "资源更新检查");
238 238
     }
239
+
240
+
241
+    @Operation(
242
+            summary = "5.1.3.7 阿里云上传接口",
243
+            description = "5.1.3.7 阿里云上传接口",
244
+            parameters = {
245
+                    @Parameter(name = "file", description = "文件", required = true)
246
+            }
247
+    )
248
+    @PostMapping("/ossUpload")
249
+    public MessageBean<String> ossUpload(MultipartFile file) {
250
+        return MessageBean.ok(baseService.ossUpload(file), "oss上传");
251
+    }
239 252
 }

+ 16 - 25
src/main/java/com/lqkj/link/module/zone/service/ResourceService.java

@@ -6,8 +6,10 @@ import com.lqkj.link.module.zone.domain.ModelCategory;
6 6
 import com.lqkj.link.module.zone.domain.ModelInfo;
7 7
 import com.lqkj.link.module.zone.repository.ModelCategoryRepository;
8 8
 import com.lqkj.link.module.zone.repository.ModelInfoRepository;
9
+import com.lqkj.link.util.AliOSSUtils;
9 10
 import com.lqkj.link.util.Unzipper;
10 11
 import org.apache.commons.compress.archivers.ArchiveException;
12
+import org.springframework.beans.factory.annotation.Autowired;
11 13
 import org.springframework.data.domain.Page;
12 14
 import org.springframework.data.domain.PageRequest;
13 15
 import org.springframework.data.domain.Pageable;
@@ -25,6 +27,9 @@ public class ResourceService {
25 27
     private final ModelInfoRepository infoRepository;
26 28
     private final UserInfoRepository userInfoRepository;
27 29
 
30
+    @Autowired
31
+    private AliOSSUtils aliOSSUtils;
32
+
28 33
     public ResourceService(ModelCategoryRepository categoryRepository, ModelInfoRepository infoRepository, UserInfoRepository userInfoRepository) {
29 34
         this.categoryRepository = categoryRepository;
30 35
         this.infoRepository = infoRepository;
@@ -72,39 +77,25 @@ public class ResourceService {
72 77
                 for (File model : models) {
73 78
                     if (model.isFile() && model.getName().endsWith(".fbx")) {
74 79
                         String modelFileName = model.getName();
75
-                        String modelPath = "/upload/resource/" + category.getCategoryId() + "/model/";
76
-                        if (modelFileName.matches(".*[一-龥]+.*")) {
77
-                            // 如果包含中文,重命名
78
-                            String newFileName = UUID.randomUUID() + ".fbx";
79
-                            modelPath += newFileName;
80
-                            boolean rename = model.renameTo(new File("." + modelPath));
80
+                        String modelPath = aliOSSUtils.upload(model);
81
+                        // 如果包含中文,重命名
82
+                        String newFileName = UUID.randomUUID() + ".png";
83
+                        String modelIconPath = "." + "/upload/resource/" + category.getCategoryId() + "/icon/" + newFileName;
84
+                        // 模型图标也许要重命名
85
+                        File oldIconFile = new File("." + "/upload/resource/" + category.getCategoryId() + "/icon/" + modelFileName.replace(".fbx", ".png"));
86
+                        if (oldIconFile.exists()) {
87
+                            File newIconFile = new File(modelIconPath);
88
+                            Boolean rename = oldIconFile.renameTo(newIconFile);
81 89
                             System.out.println(rename);
82
-                            // 材质文件也需要重命名
83
-                            File oldMaterialFile = new File("." + "/upload/resource/" + category.getCategoryId() + "/model/" + modelFileName.replace(".fbx", ".json"));
84
-                            if (oldMaterialFile.exists()) {
85
-                                File newMaterialFile = new File("." + "/upload/resource/" + category.getCategoryId() + "/model/" + newFileName.replace(".fbx", ".json"));
86
-                                rename = oldMaterialFile.renameTo(newMaterialFile);
87
-                                System.out.println(rename);
88
-                            }
89
-
90
-                            // 模型图标也许要重命名
91
-                            File oldIconFile = new File("." + "/upload/resource/" + category.getCategoryId() + "/icon/" + modelFileName.replace(".fbx", ".png"));
92
-                            if (oldIconFile.exists()) {
93
-                                File newIconFile = new File("." + "/upload/resource/" + category.getCategoryId() + "/icon/" + newFileName.replace(".fbx", ".png"));
94
-                                rename = oldIconFile.renameTo(newIconFile);
95
-                                System.out.println(rename);
96
-                            }
97
-                        } else {
98
-                            modelPath += modelFileName;
99 90
                         }
100 91
                         if (!modelInfoMap.containsKey(modelFileName.substring(0, modelFileName.lastIndexOf(".")))) {
101 92
                             list.add(new ModelInfo(null, category.getCategoryId(), modelFileName.substring(0, modelFileName.lastIndexOf(".")),
102 93
                                     null, null, null, modelPath,
103
-                                    modelPath.replace("model", "icon").replace("fbx", "png"), null, null));
94
+                                    modelIconPath.substring(1), null, null));
104 95
                         } else {
105 96
                             ModelInfo modelInfo = modelInfoMap.get(modelFileName.substring(0, modelFileName.lastIndexOf(".")));
106 97
                             modelInfo.setOriginalPath(modelPath);
107
-                            modelInfo.setModelIcon(modelPath.replace("model", "icon").replace("fbx", "png"));
98
+                            modelInfo.setModelIcon(modelIconPath.substring(1));
108 99
                             modelInfo.setJsonPath(null);
109 100
                             modelInfo.setTexturePath(null);
110 101
                             list.add(modelInfo);

+ 128 - 135
src/main/java/com/lqkj/link/module/zone/service/ZoneInfoService.java

@@ -8,10 +8,12 @@ import com.lqkj.link.module.zone.domain.*;
8 8
 import com.lqkj.link.module.zone.repository.GeomInfoRepository;
9 9
 import com.lqkj.link.module.zone.repository.ModelInfoRepository;
10 10
 import com.lqkj.link.module.zone.repository.ZoneInfoRepository;
11
+import com.lqkj.link.util.AliOSSUtils;
11 12
 import com.lqkj.link.util.Unzipper;
12 13
 import org.apache.commons.lang3.StringUtils;
13 14
 import org.locationtech.jts.geom.Coordinate;
14 15
 import org.locationtech.jts.geom.GeometryFactory;
16
+import org.springframework.beans.factory.annotation.Autowired;
15 17
 import org.springframework.data.domain.Page;
16 18
 import org.springframework.data.domain.PageRequest;
17 19
 import org.springframework.data.domain.Pageable;
@@ -19,6 +21,7 @@ import org.springframework.stereotype.Service;
19 21
 import org.springframework.transaction.annotation.Transactional;
20 22
 
21 23
 import java.io.File;
24
+import java.io.IOException;
22 25
 import java.nio.file.Files;
23 26
 import java.nio.file.Paths;
24 27
 import java.util.*;
@@ -31,6 +34,9 @@ public class ZoneInfoService {
31 34
     private final GeomInfoRepository geomInfoRepository;
32 35
     private final ModelInfoRepository modelInfoRepository;
33 36
 
37
+    @Autowired
38
+    private AliOSSUtils aliOSSUtils;
39
+
34 40
     public ZoneInfoService(ZoneInfoRepository zoneInfoRepository, UserInfoRepository userInfoRepository,
35 41
                            GeomInfoRepository geomInfoRepository, ModelInfoRepository modelInfoRepository) {
36 42
         this.zoneInfoRepository = zoneInfoRepository;
@@ -59,150 +65,137 @@ public class ZoneInfoService {
59 65
             zoneInfo.setTemplateUse(0);
60 66
         }
61 67
         ZoneInfo zoneInfo1 = zoneInfoRepository.save(zoneInfo);
62
-        try {
63
-            if (StringUtils.isNotBlank(zoneInfo.getTemplateFilePath())) {
64
-                // 清除元素与模型
65
-                geomInfoRepository.deleteAllByZoneId(zoneInfo1.getZoneId());
66
-                modelInfoRepository.deleteAllByTemplateIds(Collections.singletonList(zoneInfo1.getZoneId()));
67 68
 
68
-                // 解压压缩文件
69
-                // 文件目录格式:
70
-                // --geom.json
71
-                // --models
72
-                // ----model1.fbx 模型1文件
73
-                // ----model2.fbx 模型2文件
74
-                // ----model1.json 模型1材质
75
-                // ----model2.json 模型2材质
76
-                //
77
-                // geom.json文件总json格式:
78
-                // 	{
79
-                //		"init": {
80
-                //			"rotation": {
81
-                //				"x": 0,
82
-                //				"y": 0,
83
-                //				"z": 0,
84
-                //				"w": 0
85
-                //			},
86
-                //			"translation": {
87
-                //				"x": 0,
88
-                //				"y": 0,
89
-                //				"z": 0
90
-                //			},
91
-                //			"scale3D": {
92
-                //				"x": 0,
93
-                //				"y": 0,
94
-                //				"z": 0
95
-                //			}
96
-                //		},
97
-                //		"models": [
98
-                //			{
99
-                //				"modelPath": "model1.fbx",
100
-                //				"location": [
101
-                //					{
102
-                //						"rotation": {
103
-                //							"x": 0,
104
-                //							"y": 0,
105
-                //							"z": 0,
106
-                //							"w": 0
107
-                //						},
108
-                //						"translation": {
109
-                //							"x": 0,
110
-                //							"y": 0,
111
-                //							"z": 0
112
-                //						},
113
-                //						"scale3D": {
114
-                //							"x": 0,
115
-                //							"y": 0,
116
-                //							"z": 0
117
-                //						}
118
-                //					}
119
-                //				]
120
-                //			}
121
-                //		]
122
-                //	}
69
+        if (StringUtils.isNotBlank(zoneInfo.getTemplateFilePath())) {
70
+            // 清除元素与模型
71
+            geomInfoRepository.deleteAllByZoneId(zoneInfo1.getZoneId());
72
+            modelInfoRepository.deleteAllByTemplateIds(Collections.singletonList(zoneInfo1.getZoneId()));
73
+
74
+            // 解压压缩文件
75
+            // 文件目录格式:
76
+            // --geom.json
77
+            // --models
78
+            // ----model1.fbx 模型1文件
79
+            // ----model2.fbx 模型2文件
80
+            // ----model1.json 模型1材质
81
+            // ----model2.json 模型2材质
82
+            //
83
+            // geom.json文件总json格式:
84
+            // 	{
85
+            //		"init": {
86
+            //			"rotation": {
87
+            //				"x": 0,
88
+            //				"y": 0,
89
+            //				"z": 0,
90
+            //				"w": 0
91
+            //			},
92
+            //			"translation": {
93
+            //				"x": 0,
94
+            //				"y": 0,
95
+            //				"z": 0
96
+            //			},
97
+            //			"scale3D": {
98
+            //				"x": 0,
99
+            //				"y": 0,
100
+            //				"z": 0
101
+            //			}
102
+            //		},
103
+            //		"models": [
104
+            //			{
105
+            //				"modelPath": "model1.fbx",
106
+            //				"location": [
107
+            //					{
108
+            //						"rotation": {
109
+            //							"x": 0,
110
+            //							"y": 0,
111
+            //							"z": 0,
112
+            //							"w": 0
113
+            //						},
114
+            //						"translation": {
115
+            //							"x": 0,
116
+            //							"y": 0,
117
+            //							"z": 0
118
+            //						},
119
+            //						"scale3D": {
120
+            //							"x": 0,
121
+            //							"y": 0,
122
+            //							"z": 0
123
+            //						}
124
+            //					}
125
+            //				]
126
+            //			}
127
+            //		]
128
+            //	}
129
+            String geomJsonString = null;
130
+            try {
123 131
                 Unzipper.unZipFiles(new File("." + zoneInfo.getTemplateFilePath()), "./upload/template/" + zoneInfo1.getZoneId() + "/");
124
-                String geomJsonString = Files.readString(Paths.get("./upload/template/" + zoneInfo1.getZoneId() + "/geom.json"));
125
-                TemplateGeom templateGeom = JSON.parseObject(geomJsonString, TemplateGeom.class);
126
-
127
-                zoneInfo1.setInitLocation(templateGeom.getInit());
128
-                zoneInfoRepository.save(zoneInfo1);
129
-
130
-                List<TemplateInfo> templateInfoList = templateGeom.getModels();
131
-
132
-                String modelFolderPath = "./upload/template/" + zoneInfo1.getZoneId() + "/models";
133
-                File modelFolder = new File(modelFolderPath);
134
-                List<ModelInfo> list = new ArrayList<>();
135
-                File[] models = modelFolder.listFiles();
136
-                assert models != null;
137
-                for (File model : models) {
138
-                    if (model.isFile()) {
139
-                        String modelFileName = model.getName();
140
-                        if (modelFileName.endsWith(".fbx")) {
141
-                            String modelPath = "/upload/template/" + zoneInfo1.getZoneId() + "/models/";
142
-                            if (modelFileName.matches(".*[\u4e00-\u9fa5]+.*")) {
143
-                                // 如果包含中文,重命名
144
-                                String newFileName =UUID.randomUUID() + ".fbx";
145
-                                modelPath += newFileName;
146
-                                boolean rename = model.renameTo(new File("." + modelPath));
147
-                                System.out.println(rename);
148
-                                // 材质文件也需要重命名
149
-                                File oldMaterialFile = new File("." + "/upload/template/" + zoneInfo1.getZoneId() + "/models/" + modelFileName.replace(".fbx", ".json"));
150
-                                if (oldMaterialFile.exists()) {
151
-                                    File newMaterialFile = new File("." + "/upload/template/" + zoneInfo1.getZoneId() + "/models/" + newFileName.replace(".fbx", ".json"));
152
-                                    rename = oldMaterialFile.renameTo(newMaterialFile);
153
-                                    System.out.println(rename);
154
-                                }
155
-                            } else {
156
-                                modelPath += modelFileName;
157
-                            }
158
-                            list.add(new ModelInfo(null, null, modelFileName.substring(0, modelFileName.lastIndexOf(".")).toLowerCase(),
159
-                                    null, null, null, modelPath,
160
-                                    zoneInfo1.getThumbnail(), null, zoneInfo1.getZoneId()));
161
-                        }
132
+                geomJsonString = Files.readString(Paths.get("./upload/template/" + zoneInfo1.getZoneId() + "/geom.json"));
133
+            } catch (IOException e) {
134
+                modelInfoRepository.deleteAllByTemplateIds(Collections.singletonList(zoneInfo1.getZoneId()));
135
+                zoneInfoRepository.delete(zoneInfo1);
136
+                result.put("msg", "模板压缩文件解压失败!");
137
+                return result;
138
+            }
139
+            TemplateGeom templateGeom = JSON.parseObject(geomJsonString, TemplateGeom.class);
140
+
141
+            zoneInfo1.setInitLocation(templateGeom.getInit());
142
+            zoneInfoRepository.save(zoneInfo1);
143
+
144
+            List<TemplateInfo> templateInfoList = templateGeom.getModels();
145
+
146
+            String modelFolderPath = "./upload/template/" + zoneInfo1.getZoneId() + "/models";
147
+            File modelFolder = new File(modelFolderPath);
148
+            List<ModelInfo> list = new ArrayList<>();
149
+            File[] models = modelFolder.listFiles();
150
+            assert models != null;
151
+            for (File model : models) {
152
+                if (model.isFile()) {
153
+                    String modelFileName = model.getName();
154
+                    if (modelFileName.endsWith(".fbx")) {
155
+                        String modelPath = aliOSSUtils.upload(model);
156
+                        list.add(new ModelInfo(null, null, modelFileName.substring(0, modelFileName.lastIndexOf(".")).toLowerCase(),
157
+                                null, null, null, modelPath,
158
+                                zoneInfo1.getThumbnail(), null, zoneInfo1.getZoneId()));
162 159
                     }
163 160
                 }
164
-                List<ModelInfo> modelInfoList = modelInfoRepository.saveAll(list);
165
-                Map<String, ModelInfo> modelPathIdMap = modelInfoList
166
-                        .stream()
167
-                        .collect(Collectors.toMap(ModelInfo::getModelName, ModelInfo -> ModelInfo));
168
-
169
-                List<GeomInfo> geomInfoList = new ArrayList<>();
170
-                GeometryFactory geometryFactory = new GeometryFactory();
171
-                int j = 1;
172
-                for (TemplateInfo templateInfo : templateInfoList) {
173
-
174
-                    String modelName = templateInfo.getModelPath().substring(0, templateInfo.getModelPath().lastIndexOf(".")).toLowerCase();
175
-                    ModelInfo modelInfo = modelPathIdMap.get(modelName);
176
-                    for (int i = 0; i < templateInfo.getLocation().size(); i++) {
177
-                        JSONObject trans = templateInfo.getLocation().get(i);
178
-                        GeomInfo geomInfo = new GeomInfo();
179
-
180
-                        geomInfo.setGeomId(zoneInfo1.getZoneId() + "_" + j);
181
-                        geomInfo.setModelId(modelInfo.getModelId());
182
-                        geomInfo.setGeomName(modelInfo.getModelName());
183
-                        geomInfo.setZoneId(zoneInfo1.getZoneId());
184
-                        geomInfo.setLocking(false);
185
-
186
-                        geomInfo.setTrans(trans);
187
-                        JSONObject pointObject = trans.getJSONObject("translation");
188
-                        geomInfo.setGeom(geometryFactory.createPoint(new Coordinate(
189
-                                Double.parseDouble(pointObject.get("x").toString()),
190
-                                Double.parseDouble(pointObject.get("y").toString()),
191
-                                Double.parseDouble(pointObject.get("z").toString()))));
192
-                        j++;
193
-                        geomInfoList.add(geomInfo);
194
-                    }
161
+            }
162
+            List<ModelInfo> modelInfoList = modelInfoRepository.saveAll(list);
163
+            Map<String, ModelInfo> modelPathIdMap = modelInfoList
164
+                    .stream()
165
+                    .collect(Collectors.toMap(ModelInfo::getModelName, ModelInfo -> ModelInfo));
195 166
 
167
+            List<GeomInfo> geomInfoList = new ArrayList<>();
168
+            GeometryFactory geometryFactory = new GeometryFactory();
169
+            int j = 1;
170
+            for (TemplateInfo templateInfo : templateInfoList) {
171
+
172
+                String modelName = templateInfo.getModelPath().substring(0, templateInfo.getModelPath().lastIndexOf(".")).toLowerCase();
173
+                ModelInfo modelInfo = modelPathIdMap.get(modelName);
174
+                for (int i = 0; i < templateInfo.getLocation().size(); i++) {
175
+                    JSONObject trans = templateInfo.getLocation().get(i);
176
+                    GeomInfo geomInfo = new GeomInfo();
177
+
178
+                    geomInfo.setGeomId(zoneInfo1.getZoneId() + "_" + j);
179
+                    geomInfo.setModelId(modelInfo.getModelId());
180
+                    geomInfo.setGeomName(modelInfo.getModelName());
181
+                    geomInfo.setZoneId(zoneInfo1.getZoneId());
182
+                    geomInfo.setLocking(false);
183
+
184
+                    geomInfo.setTrans(trans);
185
+                    JSONObject pointObject = trans.getJSONObject("translation");
186
+                    geomInfo.setGeom(geometryFactory.createPoint(new Coordinate(
187
+                            Double.parseDouble(pointObject.get("x").toString()),
188
+                            Double.parseDouble(pointObject.get("y").toString()),
189
+                            Double.parseDouble(pointObject.get("z").toString()))));
190
+                    j++;
191
+                    geomInfoList.add(geomInfo);
196 192
                 }
197
-                geomInfoRepository.saveAll(geomInfoList);
198 193
 
199 194
             }
200
-        } catch (Exception e) {
201
-            modelInfoRepository.deleteAllByTemplateIds(Collections.singletonList(zoneInfo1.getZoneId()));
202
-            zoneInfoRepository.delete(zoneInfo1);
203
-            result.put("msg", "模板压缩文件解压失败!");
204
-            return result;
195
+            geomInfoRepository.saveAll(geomInfoList);
196
+
205 197
         }
198
+
206 199
         result.put("zone", zoneInfo1);
207 200
         return result;
208 201
     }

+ 67 - 0
src/main/java/com/lqkj/link/util/AliOSSUtils.java

@@ -0,0 +1,67 @@
1
+package com.lqkj.link.util;
2
+
3
+import com.aliyun.oss.OSS;
4
+import com.aliyun.oss.OSSClientBuilder;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.stereotype.Component;
7
+import org.springframework.web.multipart.MultipartFile;
8
+
9
+import java.io.File;
10
+import java.io.FileInputStream;
11
+import java.io.IOException;
12
+import java.io.InputStream;
13
+import java.util.UUID;
14
+import java.util.concurrent.Callable;
15
+
16
+@Component
17
+public class AliOSSUtils {
18
+ 
19
+    /**
20
+     * 注入AliProperties
21
+     */
22
+    private final AliProperties aliProperties;
23
+
24
+    private final ThreadPoolUtil threadPoolUtil;
25
+
26
+    public AliOSSUtils(AliProperties aliProperties, ThreadPoolUtil threadPoolUtil) {
27
+        this.aliProperties = aliProperties;
28
+        this.threadPoolUtil = threadPoolUtil;
29
+    }
30
+
31
+    /**
32
+     * 实现上传图片到OSS
33
+     */
34
+    public String upload(File file) {
35
+        String originalFilename = file.getName();
36
+        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
37
+        //上传文件到 OSS
38
+        OSS ossClient = new OSSClientBuilder().build(aliProperties.getEndpoint(), aliProperties.getAccessKeyId(), aliProperties.getAccessKeySecret());
39
+        threadPoolUtil.getTaskExecutor().execute(() -> {
40
+            ossClient.putObject(aliProperties.getBucketName(), fileName, file);
41
+            ossClient.shutdown();
42
+        });
43
+        //文件访问路径
44
+        String url = aliProperties.getEndpoint().split("//")[0] + "//" + aliProperties.getBucketName() + "." + aliProperties.getEndpoint().split("//")[1] + "/" + fileName;
45
+        // 关闭ossClient
46
+
47
+        return url;// 把上传到oss的路径返回
48
+    }
49
+
50
+    public String upload(MultipartFile file) throws IOException {
51
+        // 获取上传的文件的输入流
52
+        InputStream inputStream = file.getInputStream();
53
+        // 避免文件覆盖
54
+        String originalFilename = file.getOriginalFilename();
55
+        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
56
+        //上传文件到 OSS
57
+        OSS ossClient = new OSSClientBuilder().build(aliProperties.getEndpoint(), aliProperties.getAccessKeyId(), aliProperties.getAccessKeySecret());
58
+        threadPoolUtil.getTaskExecutor().execute(() -> {
59
+            ossClient.putObject(aliProperties.getBucketName(), fileName, inputStream);
60
+            ossClient.shutdown();
61
+        });
62
+        //文件访问路径
63
+        return aliProperties.getEndpoint().split("//")[0] + "//" + aliProperties.getBucketName() + "." + aliProperties.getEndpoint().split("//")[1] + "/" + fileName;
64
+    }
65
+
66
+ 
67
+}

+ 16 - 0
src/main/java/com/lqkj/link/util/AliProperties.java

@@ -0,0 +1,16 @@
1
+package com.lqkj.link.util;
2
+
3
+import lombok.Data;
4
+import org.springframework.boot.context.properties.ConfigurationProperties;
5
+import org.springframework.stereotype.Component;
6
+ 
7
+@Component
8
+@Data
9
+@ConfigurationProperties(prefix = "aliyun")
10
+public class AliProperties {
11
+    private String endpoint;		//Bucket域名
12
+    private String accessKeyId;		//阿里云账号AccessKey
13
+    private String accessKeySecret;	//阿里云账号AccessKey对应的秘钥
14
+    private String bucketName;		//Bucket名称
15
+
16
+}

+ 23 - 0
src/main/java/com/lqkj/link/util/ThreadPoolUtil.java

@@ -0,0 +1,23 @@
1
+package com.lqkj.link.util;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.stereotype.Component;
5
+
6
+import java.util.concurrent.Executor;
7
+
8
+@Component
9
+public class ThreadPoolUtil {
10
+
11
+    private final Executor taskExecutor;
12
+
13
+    @Autowired
14
+    public ThreadPoolUtil(Executor taskExecutor) {
15
+        this.taskExecutor = taskExecutor;
16
+    }
17
+
18
+    public Executor getTaskExecutor() {
19
+
20
+
21
+        return taskExecutor;
22
+    }
23
+}