将文件上传到腾讯云对象存储(COS,Cloud Object Storage)可以通过腾讯云提供的 SDK 实现。以下是详细的步骤和示例代码,帮助您完成文件上传操作。
步骤
-
注册腾讯云账号并创建存储桶:
(1)登录腾讯云控制台,进入 对象存储 COS。(2)创建一个存储桶(Bucket),并获取存储桶的名称和所属地域(Region)。 -
获取 API 密钥:
在腾讯云控制台的 访问管理 中,获取您的SecretId
和SecretKey
。 -
添加腾讯云 COS SDK 依赖:
在项目中引入腾讯云 COS 的 Java SDK。 -
编写 Java 代码上传文件:
使用 SDK 提供的 API 上传文件到腾讯云 COS。
依赖库
在 Maven 项目pom.xml添加以下依赖:
<dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>5.6.89</version>
</dependency>
示例代码
以下是一个完整的 Java 示例代码,演示如何将本地文件上传到腾讯云 COS:
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.exception.CosClientException;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;/*** 腾讯cos文件上传工具类**/
@Slf4j
public class TencentCOSUtil {//创建链接public static COSClient getCOSClient() {try {// 1. 初始化用户身份信息(SecretId 和 SecretKey)String accessKey = "your accessKey";String secretKey = "your secretKey";COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);// 2. 设置存储桶的地域Region region = new Region("ap-guangzhou");ClientConfig clientConfig = new ClientConfig(region);// 创建COClient实例。return new COSClient(cred, clientConfig);} catch (Exception e) {throw new BusinessException("创建腾讯云OSS连接失败");}}}
上传文件
/*** 上传文件。** @param inputStream 以流的方式上传文件* @param path 上传的文件存放路径* @param fileName 指定的文件名* @param suffix 上传的文件后缀* @return 文件在服务器上的全路径*/public static String upLoad(InputStream inputStream, String path, String fileName, String suffix, boolean signFlag) {if (inputStream == null) {return null;}String bucketName = "your bucketName";String endpoint = "your endpoint";String fileUrl = null;// 文件名格式SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.PURE_DATETIME_PATTERN);String newFileName = null;if (StrUtil.isNotBlank(fileName)) {newFileName = fileName + RandomUtil.randomString(5) + "." + suffix;} else {newFileName = sdf.format(new Date()) + RandomUtil.randomString(5) + "." + suffix;}String filePath = path + "/" + newFileName;fileUrl = endpoint + "/" + filePath;COSClient cosClient = getCOSClient();try {// 创建上传Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");// 上传文件PutObjectResult putResult = cosClient.putObject(bucketName, filePath, inputStream, objectMetadata);if (putResult != null) {fileUrl = signFlag ? generatePresignedUrl(cosClient, fileUrl) : fileUrl;}} catch (CosClientException oe) {log.error(oe.getMessage());throw oe;} finally {cosClient.shutdown();}log.info("[cosUpLoad]文件全路径fileUrl={}", fileUrl);return fileUrl;}
文件签名及设置过期时间
public static String generatePresignedUrl(COSClient cosClient, String fileUrl) {String bucketName="your bucketName";if (StrUtil.isBlankIfStr(fileUrl)) {return fileUrl;}if (cosClient == null) {cosClient = getCOSClient();}// 设置URL过期时间Date expiration = DateUtil.offsetMinute(new Date(), 3);try {String filePath = new URL(fileUrl).getPath().substring(1);filePath = URLDecoder.decode(filePath, "UTF-8");// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。URL url = cosClient.generatePresignedUrl(bucketName, filePath, expiration);return url.toString();} catch (CosClientException ce) {log.error("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with COS, "+ "such as not being able to access the network.");log.error("Error Message:" + ce.getMessage());} catch (MalformedURLException e) {log.error("[cosSignedUrl]文件地址格式有误", e);} catch (UnsupportedEncodingException e) {log.error("[cosSignedUrl]中文文件地址转换异常", e);} finally {if (cosClient != null) {cosClient.shutdown();}}return null;}
调用上传方法上传文件
public static void main(String[] args) {//从数据库查询业务数据List<UserData> projectList = new ArrayList<>();ByteArrayOutputStream out = new ByteArrayOutputStream();EasyExcel.write(out, UserData.class).sheet(0).doWrite(projectList);String fileUrl = null;try {fileUrl = TencentCOSUtil.upLoad(new ByteArrayInputStream(out.toByteArray()),"userData" + "/" + DateUtil.format(new Date(), "yyyy-MM"),"用户信息","xlsx", true);} catch (Exception e) {log.error("[userData]导出失败:", e);} finally {if (out != null) {try {out.close();} catch (IOException e) {log.error("[userData]关闭流失败", e);}}}if (fileUrl != null) {log.info("导出成功,文件fileUrl={}",fileUrl);}log.info("导出失败,文件fileUrl={}",fileUrl);}
代码说明
-
初始化身份信息:
使用SecretId
和SecretKey
创建COSCredentials
对象。 -
设置存储桶地域:
根据存储桶的地域(如ap-beijing
)创建ClientConfig
对象。 -
创建 COSClient:
使用COSCredentials
和ClientConfig
创建COSClient
实例。 -
上传文件:
指定存储桶名称、本地文件路径和文件在 COS 上的存储路径(Key)。使用PutObjectRequest
创建上传请求,并调用cosClient.putObject()
方法上传文件。 -
关闭 COSClient:
上传完成后,调用cosClient.shutdown()
关闭客户端。
关键参数
-
SecretId 和 SecretKey:腾讯云 API 密钥,用于身份验证。
-
BucketName:存储桶名称,格式为
<BucketName-APPID>
,例如examplebucket-1250000000
。 -
Region:存储桶所在地域,例如
ap-beijing
(北京)。 -
Key:文件在 COS 上的存储路径,例如
uploads/file.txt
。
注意事项
-
权限设置:
(1)确保存储桶的权限设置为允许上传。(2)如果需要公开访问,可以设置文件的访问权限为公共读。 -
文件大小限制:
单个文件上传最大支持 5 TB。如果文件较大,建议使用分块上传(SDK 也支持分块上传 API)。 -
安全性:
不要将SecretId
和SecretKey
硬编码在代码中,建议使用环境变量或配置文件管理。