(亲测有效)SpringBoot项目集成腾讯云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.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
// 1. 配置用户身份信息(secretId, secretKey)
String secretId = "您的腾讯云secretId";
String secretKey = "您的腾讯云secretKey";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2. 配置客户端的配置项(可选)
ClientConfig clientConfig = new ClientConfig();
// 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion("ap-nanjing");
// 3. 生成COS客户端
COSClient cosClient = new COSClient(cred, clientConfig);
// 4. 指定要上传的文件位置,在这里需要指定上传到COS的哪个BUCKET和对象键,即文件路径
File localFile = new File("C:\\Users\\Administrator\\Pictures\\cat.jpg");
InputStream input = new FileInputStream(localFile);
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket-1250000000", "cat.jpg", input);
// 5. 执行上传操作,并获取上传操作结果
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
System.out.println(putObjectResult);
// 6. 关闭客户端
cosClient.shutdown();
这段代码展示了如何使用腾讯云COS SDK在Java中上传文件到COS。首先配置了用户的身份信息,然后设置了客户端的配置项,并创建了COS客户端。接着,指定了要上传的文件和COS中的存储位置,并执行上传操作。最后关闭了客户端以释放资源。
评论已关闭