Forráskód Böngészése

ForegroundController 中添加一个从 jar 包读取图片文件的接口

reghao 4 hónapja
szülő
commit
6174baa9a2

+ 32 - 0
web/src/main/java/cn/reghao/bnt/web/blog/controller/ForegroundController.java

@@ -17,6 +17,10 @@ import org.springframework.data.domain.Page;
 import org.springframework.data.domain.PageRequest;
 import org.springframework.data.domain.Pageable;
 import org.springframework.data.domain.Sort;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
 import org.springframework.web.bind.ServletRequestUtils;
@@ -26,6 +30,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
 
 import jakarta.servlet.http.HttpServletRequest;
 import java.io.IOException;
+import java.io.InputStream;
 import java.net.URLDecoder;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
@@ -200,4 +205,31 @@ public class ForegroundController extends BaseController {
         String objectName =  uri1.replaceFirst("/", "");
         fileService.getFile(objectName);
     }
+
+    @Operation(summary = "默认头像", description = "N")
+    @GetMapping(value = "/avatar.jpg", produces = MediaType.APPLICATION_JSON_VALUE)
+    @Deprecated
+    public ResponseEntity<byte[]> getAvatar() throws IOException {
+        String avatarResource = "static/dist/images/avatar.jpg";
+        byte[] imageBytes = getResourceFromJar(avatarResource);
+
+        /*URL resource = Thread.currentThread().getContextClassLoader().getResource(avatarResource);
+        String avatarPath = resource.getPath();
+        System.out.println(avatarPath);
+        File file = new File(avatarPath);
+        byte[] imageBytes = Files.readAllBytes(file.toPath());*/
+
+        // 构建 HTTP 响应头
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.IMAGE_JPEG);
+        headers.setContentLength(imageBytes.length);
+
+        // 返回包含图片字节数组的 ResponseEntity
+        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
+    }
+
+    private byte[] getResourceFromJar(String resourcePath) throws IOException {
+        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
+        return resourceAsStream.readAllBytes();
+    }
 }