切换OSS为阿里云OSS,文件上传成功,文件访问还有问题

This commit is contained in:
starrySky
2024-03-23 23:11:48 +08:00
parent 0fb5cc8145
commit 92d239286e
16 changed files with 251 additions and 296 deletions

View File

@@ -93,31 +93,13 @@
<groupId>com.github.gavlyukovskiy</groupId>
<artifactId>p6spy-spring-boot-starter</artifactId>
</dependency>
<!--腾讯云 COS 对象存储-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<exclusions>
<exclusion>
<artifactId>tencentcloud-sdk-java-common</artifactId>
<groupId>com.tencentcloudapi</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos-sts_api</artifactId>
</dependency>
<!-- Transmittable ThreadLocal -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>

View File

@@ -1,56 +0,0 @@
package com.starry.common.config;
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.region.Region;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author admin
* 腾讯云cos对象存储配置类
* @since 2022/10/28
*/
@Data
@Component
@ConfigurationProperties(prefix = "cos")
public class CosConfig {
/**
* 存储桶访问路径
**/
private String baseUrl;
/**
* 腾讯云账号秘钥
**/
private String secretId;
/**
* 密码秘钥
**/
private String secretKey;
/**
* 存储桶地区
**/
private String regionName;
/**
* 存储桶名称
**/
private String bucketName;
/**
* 上传的根目录
**/
private String folderPrefix;
public COSClient getCosClient() {
// 初始化用户信息
COSCredentials cosCredentials = new BasicCOSCredentials(this.secretId, this.secretKey);
// 设置地域
Region region = new Region(this.regionName);
ClientConfig config = new ClientConfig(region);
// 生成COS客户端
return new COSClient(cosCredentials, config);
}
}

View File

@@ -1,83 +0,0 @@
package com.starry.common.controller;
import com.starry.common.result.R;
import com.starry.common.utils.file.CosClientUtils;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.TreeMap;
/**
* @author admin
* cos存储前端控制器
* @since 2022/11/13 17:51
*/
@Slf4j
@RestController
@RequestMapping("/cos")
public class CosController {
@Value("${cos.secretId}")
private String secretId;
@Value("${cos.secretKey}")
private String secretKey;
@Value("${cos.regionName}")
private String regionName;
@Value("${cos.bucketName}")
private String bucketName;
@ApiOperation(value = "照片上传")
@PostMapping("/upload/image")
public R uploadImage(MultipartFile file) throws Exception {
if (!file.isEmpty()) {
String avatar = CosClientUtils.upload(file, "house");
return R.ok(avatar);
}
return R.error("上传照片异常,请联系管理员");
}
@ApiOperation(value = "获取cos临时密钥")
@GetMapping("/temp-key")
public R getTempKey() {
TreeMap<String, Object> config = new TreeMap<>();
try {
// 替换为您的云 api 密钥 SecretId
config.put("secretId", secretId);
// 替换为您的云 api 密钥 SecretKey
config.put("secretKey", secretKey);
// 临时密钥有效时长,单位是秒,默认 1800 秒,目前主账号最长 2 小时(即 7200 秒),子账号最长 36 小时(即 129600
config.put("durationSeconds", 1800);
// 换成您的 bucket
config.put("bucket", bucketName);
// 换成 bucket 所在地区
config.put("region", regionName);
// 只允许用户访问 upload/house 目录下的资源
config.put("allowPrefixes", new String[]{"upload/house/*"});
// 密钥的权限列表。必须在这里指定本次临时密钥所需要的权限。
String[] allowActions = new String[]{
// 简单上传
"name/cos:PutObject",
// 表单上传、小程序上传
"name/cos:PostObject",
// 分块上传
"name/cos:InitiateMultipartUpload", "name/cos:ListMultipartUploads", "name/cos:ListParts", "name/cos:UploadPart", "name/cos:CompleteMultipartUpload"};
config.put("allowActions", allowActions);
Response response = CosStsClient.getCredential(config);
return R.ok(response);
} catch (Exception e) {
log.error("getTempKey error", e);
throw new IllegalArgumentException("no valid secret !");
}
}
}

View File

@@ -1,95 +0,0 @@
package com.starry.common.utils.file;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.starry.common.config.CosConfig;
import com.starry.common.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author admin
* 腾讯云COS文件上传工具类
* @since 2022/10/31
*/
@Slf4j
public class CosClientUtils {
/**
* 获取配置信息
*/
private static final CosConfig cosConfig = SpringUtils.getBean(CosConfig.class);
public static String upload(MultipartFile file, String dir) throws Exception {
String originalFilename = file.getOriginalFilename();
// 文件名
String name = FilenameUtils.getBaseName(originalFilename) + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
// 目录
String folderName = cosConfig.getFolderPrefix() + "/" + dir + "/";
String key = folderName + name;
File localFile = null;
try {
localFile = transferToFile(file);
String filePath = uploadFileToCos(localFile, key);
log.info("upload COS successful: {}", filePath);
return filePath;
} catch (Exception e) {
throw new Exception("文件上传失败");
} finally {
localFile.delete();
}
}
/**
* 用缓冲区来创建临时文件
* 使用 MultipartFile.transferTo()
*
* @param multipartFile
* @return
*/
private static File transferToFile(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
String prefix = originalFilename.split("\\.")[0];
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
File file = File.createTempFile(prefix, suffix);
multipartFile.transferTo(file);
return file;
}
/**
* 上传文件到COS
*
* @param localFile
* @param key
* @return
*/
private static String uploadFileToCos(File localFile, String key) throws InterruptedException {
PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, localFile);
// 获取连接
COSClient cosClient = cosConfig.getCosClient();
// 创建线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(8, 16,
4, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.AbortPolicy());
// 传入一个threadPool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池
TransferManager transferManager = new TransferManager(cosClient, threadPool);
// 返回一个异步结果Upload, 可同步的调用waitForUploadResult等待upload结束, 成功返回UploadResult, 失败抛出异常
Upload upload = transferManager.upload(putObjectRequest);
UploadResult uploadResult = upload.waitForUploadResult();
transferManager.shutdownNow();
cosClient.shutdown();
String filePath = cosConfig.getBaseUrl() + uploadResult.getKey();
return filePath;
}
}