zhentao 3 weeks ago
parent
commit
5cd2fef683

+ 16 - 0
pom.xml

@@ -15,6 +15,22 @@
     </properties>
     </properties>
     <dependencies>
     <dependencies>
         <dependency>
         <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.17.4</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.xml.bind</groupId>
+            <artifactId>jaxb-api</artifactId>
+            <version>2.3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.activation</groupId>
+            <artifactId>activation</artifactId>
+            <version>1.1.1</version>
+        </dependency>
+
+        <dependency>
             <groupId>io.jsonwebtoken</groupId>
             <groupId>io.jsonwebtoken</groupId>
             <artifactId>jjwt</artifactId>
             <artifactId>jjwt</artifactId>
             <version>0.9.1</version>
             <version>0.9.1</version>

+ 2 - 0
src/main/java/com/zhentao/information/controller/MessageController.java

@@ -1,6 +1,7 @@
 package com.zhentao.information.controller;
 package com.zhentao.information.controller;
 
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
+import com.zhentao.config.NullLogin;
 import com.zhentao.information.entity.ChatMessage;
 import com.zhentao.information.entity.ChatMessage;
 import com.zhentao.information.entity.Message;
 import com.zhentao.information.entity.Message;
 import com.zhentao.information.handler.WebSocketHandler;
 import com.zhentao.information.handler.WebSocketHandler;
@@ -32,6 +33,7 @@ public class MessageController {
      * 发送消息接口
      * 发送消息接口
      */
      */
     @PostMapping("/send")
     @PostMapping("/send")
+    @NullLogin
     public String sendMessage(@RequestBody Message message) {
     public String sendMessage(@RequestBody Message message) {
         log.info("收到消息:发送者={}, 接收者={}, 内容={}",
         log.info("收到消息:发送者={}, 接收者={}, 内容={}",
                 message.getFromUserId(),
                 message.getFromUserId(),

+ 4 - 4
src/main/java/com/zhentao/intercepoter/Userinterceptor.java

@@ -22,16 +22,16 @@ public class Userinterceptor implements HandlerInterceptor {
 //            return true;
 //            return true;
 //        }
 //        }
         String token = request.getHeader("token");
         String token = request.getHeader("token");
-        if (token==null){
-            System.err.println("Token不能为空");
-            return false;
-        }
         HandlerMethod handlerMethod = (HandlerMethod) handler;
         HandlerMethod handlerMethod = (HandlerMethod) handler;
         NullLogin annotation = handlerMethod.getMethod().getAnnotation(NullLogin.class);
         NullLogin annotation = handlerMethod.getMethod().getAnnotation(NullLogin.class);
         System.err.println("自定义注解"+annotation);
         System.err.println("自定义注解"+annotation);
         if (annotation!=null){
         if (annotation!=null){
             return true;
             return true;
         }
         }
+        if (token==null){
+            System.err.println("Token不能为空");
+            return false;
+        }
         String userIdFromToken = TokenUtils.getUserIdFromToken(token);
         String userIdFromToken = TokenUtils.getUserIdFromToken(token);
         System.err.println("解析后的ID:"+userIdFromToken);
         System.err.println("解析后的ID:"+userIdFromToken);
         String s = redisTemplate.opsForValue().get(userIdFromToken);
         String s = redisTemplate.opsForValue().get(userIdFromToken);

+ 110 - 0
src/main/java/com/zhentao/oss/controller/ossController.java

@@ -0,0 +1,110 @@
+package com.zhentao.oss.controller;
+
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.aliyun.oss.model.PutObjectRequest;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+@RestController
+@RequestMapping("/api/upload")
+public class ossController {
+
+    @Value("${aliyun.oss.endpoint}")
+    private String endpoint;
+
+    @Value("${aliyun.oss.accessKeyId}")
+    private String accessKeyId;
+
+    @Value("${aliyun.oss.accessKeySecret}")
+    private String accessKeySecret;
+
+    @Value("${aliyun.oss.bucketName}")
+    private String bucketName;
+
+    // 允许的图片格式
+    private static final String[] ALLOWED_TYPES = {
+            "image/jpeg", "image/png", "image/gif"
+    };
+
+    @PostMapping("/simple-image")
+    public Map<String, Object> uploadSimpleImage(@RequestParam("file") MultipartFile file) {
+        Map<String, Object> result = new HashMap<>();
+
+        // 基础验证
+        if (file == null || file.isEmpty()) {
+            result.put("code", 400);
+            result.put("message", "上传图片不能为空");
+            return result;
+        }
+
+        // 验证图片格式
+        String contentType = file.getContentType();
+        if (!isValidImageType(contentType)) {
+            result.put("code", 400);
+            result.put("message", "仅支持JPG、PNG、GIF格式的图片");
+            return result;
+        }
+
+        OSS ossClient = null;
+        try {
+            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+            // 生成唯一文件名
+            String originalFilename = file.getOriginalFilename();
+            String extension = getFileExtension(originalFilename);
+            String fileName = UUID.randomUUID().toString() + "." + extension;
+
+            // 上传图片
+            PutObjectRequest putObjectRequest = new PutObjectRequest(
+                    bucketName, fileName, file.getInputStream()
+            );
+            ossClient.putObject(putObjectRequest);
+
+            // 构建访问URL
+            String endpointWithoutProtocol = endpoint.replaceFirst("^https?://", "");
+            String imageUrl = "https://" + bucketName + "." + endpointWithoutProtocol + "/" + fileName;
+
+            // 返回结果
+            result.put("code", 200);
+            result.put("message", "图片上传成功");
+            result.put("imageUrl", imageUrl);
+
+        } catch (IOException e) {
+            result.put("code", 500);
+            result.put("message", "上传失败:" + e.getMessage());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+
+        return result;
+    }
+
+    private boolean isValidImageType(String contentType) {
+        if (contentType == null) return false;
+        for (String type : ALLOWED_TYPES) {
+            if (contentType.equalsIgnoreCase(type)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private String getFileExtension(String fileName) {
+        if (fileName == null || !fileName.contains(".")) {
+            return "jpg";
+        }
+        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
+    }
+}

+ 6 - 0
src/main/resources/application.yml

@@ -33,3 +33,9 @@ spring:
     host: 47.110.46.22
     host: 47.110.46.22
     port: 6379
     port: 6379
     database: 0
     database: 0
+aliyun:
+  oss:
+    endpoint: https://oss-cn-beijing.aliyuncs.com
+    accessKeyId: LTAI5tH3XWv25v5LyeapQq1K
+    accessKeySecret: pEP2P1ezDkPZJwuMFkdrqVNRTlATok
+    bucketName: wangyongchun