• 从0到1,申请cos服务器并上传图片到cos文件服务器


    目录

    准备工作

    Java代码编写

    控制台打印

    整理成工具类

    编写接口

    Postman测试


    准备工作

    1.进入网址
    腾讯云 产业智变·云启未来 - 腾讯 (tencent.com)

    2.搜索cos,点击立即使用,刚开始会免费赠送你

    3.存储都是基于桶的,先创建桶,在桶里面创建文件夹,所以点击创建桶

    4.查看桶列表,点击左侧

    5.点进去,创建文件夹,我这里创建了两个文件夹

    6.桶搞完了,要拿到 secretId secretKey,进入下面的地址
    登录 - 腾讯云
    点击新建密钥,创建自己的密钥

    以上准备工作就做完了,下面进行代码测试


    Java代码编写

    1. package com.zsp.quartz.util.OSS;
    2. import com.qcloud.cos.COSClient;
    3. import com.qcloud.cos.ClientConfig;
    4. import com.qcloud.cos.auth.BasicCOSCredentials;
    5. import com.qcloud.cos.auth.COSCredentials;
    6. import com.qcloud.cos.exception.CosClientException;
    7. import com.qcloud.cos.exception.CosServiceException;
    8. import com.qcloud.cos.http.HttpProtocol;
    9. import com.qcloud.cos.model.*;
    10. import com.qcloud.cos.region.Region;
    11. import java.io.File;
    12. import java.net.URL;
    13. import java.time.LocalDateTime;
    14. import java.util.Date;
    15. import java.util.UUID;
    16. public class getOSSToken {
    17. public static void main(String[] args) {
    18. // 初始化客户端
    19. String secretId = "xxxxxx";
    20. String secretKey = "xxxxxx";
    21. COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    22. Region region = new Region("ap-nanjing");
    23. ClientConfig clientConfig = new ClientConfig(region);
    24. clientConfig.setHttpProtocol(HttpProtocol.https);
    25. COSClient cosClient = new COSClient(cred, clientConfig);
    26. //定义存储桶
    27. String bucket = "zsp-image-xxxxxx"; //存储桶名称,格式:BucketName-APPID
    28. // 上传文件
    29. File localFile = new File("C:/Users/UU/Desktop/我的/生活照.jpeg");
    30. // 指定文件上传到 COS 上的路径,即对象键。
    31. String path = "image/"+ LocalDateTime.now() +"file"+ UUID.randomUUID()+".jpeg";
    32. // 三个参数:桶名,文件夹路径,文件
    33. PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, localFile);
    34. System.out.println("key为:"+putObjectRequest.getKey()); // image/2023-10-18T11:58:25.792fileef9bb4a9-3b0a-49f1-92a4-5bc3f3572977.jpeg
    35. // 上传到oss
    36. cosClient.putObject(putObjectRequest);
    37. // 得到图片地址
    38. Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
    39. // 三个参数:桶名,文件名,过期时间
    40. URL url = cosClient.generatePresignedUrl(bucket, putObjectRequest.getKey(), expiration);
    41. System.out.println(url.toString());
    42. //关闭资源
    43. cosClient.shutdown();
    44. }
    45. }

    控制台打印

    整理成工具类

    1. package com.zsp.quartz.util.COS;
    2. import cn.hutool.core.date.DateUtil;
    3. import com.qcloud.cos.COSClient;
    4. import com.qcloud.cos.ClientConfig;
    5. import com.qcloud.cos.auth.BasicCOSCredentials;
    6. import com.qcloud.cos.auth.COSCredentials;
    7. import com.qcloud.cos.http.HttpProtocol;
    8. import com.qcloud.cos.model.*;
    9. import com.qcloud.cos.region.Region;
    10. import org.springframework.web.multipart.MultipartFile;
    11. import java.io.IOException;
    12. import java.io.InputStream;
    13. import java.net.URL;
    14. import java.util.Date;
    15. import java.util.Random;
    16. public class COSUpload {
    17. private static String secretId = "asdkhjahsdkjhasjkdhas";
    18. private static String secretKey = "asmdiuoahuihas";
    19. private static String bucket = "zsp-image-xxxxxxxx";
    20. private static String fileFolder = "image/";
    21. private static COSClient cosClient;
    22. static {
    23. COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    24. Region region = new Region("ap-nanjing");
    25. ClientConfig clientConfig = new ClientConfig(region);
    26. clientConfig.setHttpProtocol(HttpProtocol.https);
    27. cosClient = new COSClient(cred, clientConfig);
    28. }
    29. public static String uploadFileToCOS(MultipartFile file) throws IOException {
    30. String originalFilename = file.getOriginalFilename();
    31. String substring;
    32. if (originalFilename.contains(".")) {
    33. substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    34. } else {
    35. substring = originalFilename;
    36. }
    37. Random random = new Random();
    38. String fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
    39. InputStream inputStream = null;
    40. inputStream = file.getInputStream();
    41. return uploadFileCOS(inputStream, fileName, fileFolder);
    42. }
    43. public static String uploadFileCOS(InputStream instream, String fileName, String fileFolder) {
    44. String ret = "";
    45. try {
    46. // 创建上传Object的Metadata
    47. ObjectMetadata objectMetadata = new ObjectMetadata();
    48. objectMetadata.setContentLength(instream.available());
    49. objectMetadata.setCacheControl("no-cache");
    50. objectMetadata.setHeader("Pragma", "no-cache");
    51. if (fileName.contains(".")) {
    52. objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
    53. } else {
    54. objectMetadata.setContentType(getcontentType(fileName));
    55. }
    56. objectMetadata.setContentDisposition("inline;filename=" + fileName);
    57. String filePath = fileFolder + DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + fileName;
    58. // 上传文件
    59. PutObjectRequest data = new PutObjectRequest(bucket, filePath, instream, objectMetadata);
    60. cosClient.putObject(data);
    61. Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
    62. // 三个参数:桶名,文件名,过期时间
    63. URL url = cosClient.generatePresignedUrl(bucket, data.getKey(), expiration);
    64. ret = url.toString();
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. } finally {
    68. try {
    69. if (instream != null) {
    70. instream.close();
    71. }
    72. } catch (IOException e) {
    73. e.printStackTrace();
    74. }
    75. }
    76. return ret;
    77. }
    78. public static String getcontentType(String FilenameExtension) {
    79. if (FilenameExtension.equalsIgnoreCase(".bmp")) {
    80. return "image/bmp";
    81. }
    82. if (FilenameExtension.equalsIgnoreCase(".gif")) {
    83. return "image/gif";
    84. }
    85. if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg")
    86. || FilenameExtension.equalsIgnoreCase(".png")) {
    87. return "image/jpeg";
    88. }
    89. if (FilenameExtension.equalsIgnoreCase(".html")) {
    90. return "text/html";
    91. }
    92. if (FilenameExtension.equalsIgnoreCase(".txt")) {
    93. return "text/plain";
    94. }
    95. if (FilenameExtension.equalsIgnoreCase(".vsd")) {
    96. return "application/vnd.visio";
    97. }
    98. if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
    99. return "application/vnd.ms-powerpoint";
    100. }
    101. if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
    102. return "application/msword";
    103. }
    104. if (FilenameExtension.equalsIgnoreCase(".xml")) {
    105. return "text/xml";
    106. }
    107. if (FilenameExtension.equalsIgnoreCase(".pdf")) {
    108. return "application/pdf";
    109. }
    110. return "image/jpeg";
    111. }
    112. }

    编写接口

    1. /**
    2. * 图片上传
    3. * @param file
    4. * @return
    5. * @throws Exception
    6. */
    7. private final static int maxSize = 15 * 1024 * 1024;
    8. @PostMapping("/oss/upload")
    9. public Result uploadFile(@RequestParam("file")MultipartFile file) throws Exception {
    10. //检查文件是否为空
    11. if (file.isEmpty()) return Result.fail("请选择图片");
    12. //检查文件大小
    13. if (file.getSize() > maxSize) return Result.fail("请上传15M以内的图片");
    14. final String url = COSUpload.uploadFileToCOS(file);
    15. ImageResult imageResult = new ImageResult(url);
    16. return Result.success(url);
    17. }

    Postman测试

    COS服务器显示

    按照时间节点创建日期文件夹进行存储。

  • 相关阅读:
    2023 年和 2024 年 10 个最佳加密货币趋势
    DV SSL证书
    乡村研学|乡村研学小程序|基于微信小程序的乡村研学平台设计与实现(源码+数据库+文档)
    企业工程项目管理系统源码(三控:进度组织、质量安全、预算资金成本、二平台:招采、设计管理)
    如何通过ip查询用户的归属地
    c#数组次序统计系列1
    pip 指定源
    YOLOV5通道剪枝【附代码】
    【Segment Anything Model】八:修改SAM源码做分类任务
    YOLO v3源码详解
  • 原文地址:https://blog.csdn.net/m0_55627541/article/details/133902798