From b844453877db2b534106383497fc55fbdfc6a427 Mon Sep 17 00:00:00 2001
From: zqy <2522236926@qq.com>
Date: 星期二, 25 三月 2025 21:12:13 +0800
Subject: [PATCH] 对象存储的上传下载删除接口
---
ruoyi-admin/pom.xml | 17 +++
zhang-content/src/main/java/com/ruoyi/service/impl/GetOrPut.java | 146 +++++++++++++++++++++++++++++
ruoyi-admin/src/main/java/com/ruoyi/web/controller/zhang/CosController.java | 91 ++++++++++++++++++
ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java | 9 +
zhang-content/pom.xml | 28 +++++
ruoyi-admin/src/main/resources/application.yml | 8 +
ruoyi-common/pom.xml | 1
7 files changed, 300 insertions(+), 0 deletions(-)
diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml
index 408c1a6..0c8e112 100644
--- a/ruoyi-admin/pom.xml
+++ b/ruoyi-admin/pom.xml
@@ -77,6 +77,23 @@
<artifactId>ruoyi-common</artifactId>
</dependency>
+ <!-- 鑵捐浜� -->
+ <dependency>
+ <groupId>com.qcloud</groupId>
+ <artifactId>cos_api</artifactId>
+ <version>5.6.227</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
</dependencies>
<build>
diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/zhang/CosController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/zhang/CosController.java
new file mode 100644
index 0000000..896b427
--- /dev/null
+++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/zhang/CosController.java
@@ -0,0 +1,91 @@
+package com.ruoyi.web.controller.zhang;
+
+import com.qcloud.cos.utils.IOUtils;
+import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.service.impl.GetOrPut;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+
+@RestController
+@RequestMapping("/cos")
+public class CosController {
+
+ @Autowired
+ private GetOrPut getOrPut;
+
+ // 鏂囦欢涓婁紶
+ @PostMapping("/upload")
+ public AjaxResult upload(@RequestParam("file") MultipartFile file) {
+ String key;
+ try {
+ key = getOrPut.uploadFile(file);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ System.out.println("dfsdgd");
+ HashMap<String,String> map = new HashMap<>();
+ map.put("key",key);
+ return AjaxResult.success(map);
+ }
+
+ // 鏂囦欢涓嬭浇
+ @GetMapping("/download")
+ public void download(@RequestParam String key, HttpServletResponse response) {
+ try (InputStream inputStream = getOrPut.getFileStream(key)) {
+
+ String fileExtension = getFileExtension(key);
+ String contentType = getContentType(fileExtension);
+
+ response.setContentType(contentType);
+
+ response.setHeader("Content-Disposition", "attachment; filename=\"" + key + "\"");
+ IOUtils.copy(inputStream, response.getOutputStream());
+ } catch (IOException e) {
+ throw new RuntimeException("鏂囦欢涓嬭浇澶辫触", e);
+ }
+ }
+
+
+ private String getFileExtension(String key) {
+ int dotIndex = key.lastIndexOf('.');
+ if (dotIndex == -1) {
+ return ""; // 娌℃湁鎵╁睍鍚�
+ }
+ return key.substring(dotIndex + 1).toLowerCase();
+ }
+
+ private String getContentType(String fileExtension) {
+ switch (fileExtension) {
+ case "jpg":
+ case "jpeg":
+ return "image/jpeg";
+ case "png":
+ return "image/png";
+ case "gif":
+ return "image/gif";
+ case "pdf":
+ return "application/pdf";
+ case "txt":
+ return "text/plain";
+ default:
+ return "application/octet-stream"; // 榛樿绫诲瀷
+ }
+ }
+
+ @DeleteMapping("/delete")
+ public AjaxResult delete(@RequestParam String key){
+ try {
+ getOrPut.deleteFile(key);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return AjaxResult.success("鏂囦欢涓婁紶鎴愬姛");
+ }
+}
\ No newline at end of file
diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml
index 4aece0c..6032dc1 100644
--- a/ruoyi-admin/src/main/resources/application.yml
+++ b/ruoyi-admin/src/main/resources/application.yml
@@ -144,3 +144,11 @@
# 鍖归厤閾炬帴
urlPatterns: /system/*,/monitor/*,/tool/*
+#鑵捐浜�
+tencent:
+ cos:
+ secret-id: AKIDOelfP1QbZJq9E5j9LI2YptwlNlvsbBf0 # 鏇挎崲涓哄疄闄匰ecretId
+ secret-key: DCxVpvnRt89wVs2ygATYZWOMFzXtAHB3 # 鏇挎崲涓哄疄闄匰ecretKey
+ bucket-name: examplebucket-22222-1346631008 # 瀛樺偍妗跺悕绉�
+ region: ap-guangzhou # 瀛樺偍妗跺湴鍩�
+ base-url: https://examplebucket-22222-1346631008.cos.ap-guangzhou.myqcloud.com # 璁块棶鍩虹URL
\ No newline at end of file
diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml
index 15eb4c0..67e2fe8 100644
--- a/ruoyi-common/pom.xml
+++ b/ruoyi-common/pom.xml
@@ -181,6 +181,7 @@
</dependency>
+
</dependencies>
<build>
diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java b/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java
index a1bcfe2..787da47 100644
--- a/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java
+++ b/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java
@@ -34,6 +34,15 @@
{
requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
}
+
+ else if (request instanceof HttpServletRequest
+ && StringUtils.startsWithIgnoreCase(request.getContentType(), "image/"))
+ {
+ // 瀵逛簬鍥剧墖璇锋眰锛屼笉鍋氫换浣曞寘瑁�
+ chain.doFilter(request, response);
+ return; // 鐩存帴杩斿洖锛岄伩鍏嶅悗缁殑浠g爜鎵ц
+ }
+
if (null == requestWrapper)
{
chain.doFilter(request, response);
diff --git a/zhang-content/pom.xml b/zhang-content/pom.xml
index 5fc59a4..c94faf8 100644
--- a/zhang-content/pom.xml
+++ b/zhang-content/pom.xml
@@ -73,6 +73,34 @@
<artifactId>spring-test</artifactId>
</dependency>
+ <!-- 鑵捐浜� -->
+ <dependency>
+ <groupId>com.qcloud</groupId>
+ <artifactId>cos_api</artifactId>
+ <version>5.6.227</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>2.8.8</version>
+ </dependency>
+
</dependencies>
<build>
diff --git a/zhang-content/src/main/java/com/ruoyi/service/impl/GetOrPut.java b/zhang-content/src/main/java/com/ruoyi/service/impl/GetOrPut.java
new file mode 100644
index 0000000..f23b112
--- /dev/null
+++ b/zhang-content/src/main/java/com/ruoyi/service/impl/GetOrPut.java
@@ -0,0 +1,146 @@
+package com.ruoyi.service.impl;
+
+import com.qcloud.cos.COSClient;
+import com.qcloud.cos.ClientConfig;
+import com.qcloud.cos.auth.BasicCOSCredentials;
+import com.qcloud.cos.auth.COSCredentials;
+import com.qcloud.cos.http.HttpProtocol;
+import com.qcloud.cos.model.*;
+import com.qcloud.cos.region.Region;
+import com.qcloud.cos.transfer.TransferManager;
+import com.qcloud.cos.transfer.TransferManagerConfiguration;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.PostConstruct;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+@Service
+@ConfigurationProperties(prefix = "tencent.cos")
+public class GetOrPut {
+ // 浠庨厤缃枃浠惰鍙栫殑鍙傛暟
+ private String secretId;
+ private String secretKey;
+ private String bucketName;
+ private String region;
+ private String baseUrl;
+
+ private COSClient cosClient;
+ private TransferManager transferManager;
+
+ // 鍒濆鍖栭厤缃�
+ @PostConstruct
+ private void init() {
+ // 1. 鍒濆鍖栫敤鎴疯韩浠戒俊鎭�
+ COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
+
+ // 2. 璁剧疆bucket鐨勫尯鍩�
+ Region region = new Region(this.region);
+ ClientConfig clientConfig = new ClientConfig(region);
+ clientConfig.setHttpProtocol(HttpProtocol.https);
+
+ // 3. 鐢熸垚cos瀹㈡埛绔�
+ cosClient = new COSClient(cred, clientConfig);
+
+ // 4. 鍒濆鍖栦紶杈撶鐞嗗櫒锛堢敤浜庡ぇ鏂囦欢涓婁紶锛�
+ ExecutorService threadPool = Executors.newFixedThreadPool(32);
+ TransferManagerConfiguration transferConfig = new TransferManagerConfiguration();
+ transferConfig.setMultipartUploadThreshold(5 * 1024 * 1024);
+ transferManager = new TransferManager(cosClient, threadPool);
+ transferManager.setConfiguration(transferConfig);
+ }
+
+ /**
+ * 涓婁紶鏂囦欢锛圡ultipartFile鏂瑰紡锛�
+ * @param file 涓婁紶鐨勬枃浠�
+ * @return 鏂囦欢璁块棶URL
+ */
+ public String uploadFile(MultipartFile file) {
+ try {
+ // 鐢熸垚鍞竴鏂囦欢鍚�
+ String originalFilename = file.getOriginalFilename();
+ String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
+ String key = java.util.UUID.randomUUID().toString() + fileExt;
+
+ ObjectMetadata metadata = new ObjectMetadata();
+ metadata.setContentLength(file.getSize());
+ metadata.setContentType(file.getContentType());
+
+ PutObjectRequest putObjectRequest = new PutObjectRequest(
+ bucketName,
+ key,
+ file.getInputStream(),
+ metadata
+ );
+
+ // 涓婁紶鏂囦欢
+ PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
+ return baseUrl + "/" + key;
+ } catch (IOException e) {
+ throw new RuntimeException("鏂囦欢涓婁紶澶辫触", e);
+ }
+ }
+
+ /**
+ * 涓婁紶鏈湴鏂囦欢
+ * @param localFilePath 鏈湴鏂囦欢璺緞
+ * @return 鏂囦欢璁块棶URL
+ */
+ public String uploadLocalFile(String localFilePath) {
+ File localFile = new File(localFilePath);
+ String key = UUID.randomUUID().toString() + getFileExtension(localFile.getName());
+
+ PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
+ cosClient.putObject(putObjectRequest);
+ return baseUrl + "/" + key;
+ }
+
+ /**
+ * 涓嬭浇鏂囦欢鍒版湰鍦�
+ * @param key 鏂囦欢鍞竴鏍囪瘑
+ * @param localFilePath 鏈湴瀛樺偍璺緞
+ */
+ public void downloadFile(String key, String localFilePath) {
+ File downFile = new File(localFilePath);
+ GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
+ cosClient.getObject(getObjectRequest, downFile);
+ }
+
+ /**
+ * 鑾峰彇鏂囦欢杈撳叆娴�
+ * @param key 鏂囦欢鍞竴鏍囪瘑
+ * @return 鏂囦欢杈撳叆娴�
+ */
+ public InputStream getFileStream(String key) {
+ COSObject cosObject = cosClient.getObject(bucketName, key);
+ return cosObject.getObjectContent();
+ }
+
+ /**
+ * 鍒犻櫎鏂囦欢
+ * @param key 鏂囦欢鍞竴鏍囪瘑
+ */
+ public void deleteFile(String key) {
+ cosClient.deleteObject(bucketName, key);
+ }
+
+ // 鑾峰彇鏂囦欢鎵╁睍鍚�
+ private String getFileExtension(String fileName) {
+ return fileName.substring(fileName.lastIndexOf("."));
+ }
+
+ // Getter/Setter 鐢ㄤ簬閰嶇疆娉ㄥ叆
+ public void setSecretId(String secretId) { this.secretId = secretId; }
+ public void setSecretKey(String secretKey) { this.secretKey = secretKey; }
+ public void setBucketName(String bucketName) { this.bucketName = bucketName; }
+ public void setRegion(String region) { this.region = region; }
+ public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
+}
--
Gitblit v1.9.1