• cos文件上传demo (精简版通用)


    1. 依赖

    1. <!--腾讯云cos依赖-->
    2. <dependency>
    3. <groupId>com.qcloud</groupId>
    4. <artifactId>cos_api</artifactId>
    5. <version>5.6.54</version>
    6. </dependency>

    2. FileController

    1. import com.ruoyi.common.core.domain.AjaxResult;
    2. import com.ruoyi.common.utils.file.FileUtils;
    3. import io.swagger.annotations.Api;
    4. import io.swagger.annotations.ApiOperation;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.PostMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RequestPart;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import org.springframework.web.multipart.MultipartFile;
    12. import java.security.SecureRandom;
    13. import java.text.SimpleDateFormat;
    14. import java.util.Date;
    15. @Slf4j
    16. @Api(value = "文件", tags = {"文件"})
    17. @RestController
    18. @RequestMapping("/file/upload")
    19. public class FileController {
    20. @Autowired
    21. private COSUtils cosUtils;
    22. @ApiOperation("文件上传")
    23. @PostMapping
    24. public AjaxResult upload(@RequestPart("file") MultipartFile file){
    25. try {
    26. String url = "";
    27. // 获取后缀名
    28. String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    29. // 最后上传生成的文件名
    30. String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
    31. // oss中的文件夹名
    32. String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + finalFileName;
    33. // 上传oss
    34. cosUtils.uploadFileCOS(file.getInputStream(), objectName);
    35. //获取文件的URl地址
    36. url = cosUtils.getUrl(objectName);
    37. log.info("url: {}",url);
    38. AjaxResult ajax = AjaxResult.success();
    39. ajax.put("url", url);
    40. ajax.put("fileName", file.getOriginalFilename());
    41. ajax.put("newFileName", FileUtils.getName(finalFileName));
    42. return ajax;
    43. } catch (Exception e) {
    44. return AjaxResult.error(e.getMessage());
    45. }
    46. }
    47. }

     
    
    3. AjaxResult
    1. import java.util.HashMap;
    2. import com.ruoyi.common.constant.HttpStatus;
    3. import com.ruoyi.common.utils.StringUtils;
    4. /**
    5. * 操作消息提醒
    6. *
    7. */
    8. public class AjaxResult extends HashMap<String, Object>
    9. {
    10. private static final long serialVersionUID = 1L;
    11. /** 状态码 */
    12. public static final String CODE_TAG = "code";
    13. /** 返回内容 */
    14. public static final String MSG_TAG = "msg";
    15. /** 数据对象 */
    16. public static final String DATA_TAG = "data";
    17. /**
    18. * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
    19. */
    20. public AjaxResult()
    21. {
    22. }
    23. /**
    24. * 初始化一个新创建的 AjaxResult 对象
    25. *
    26. * @param code 状态码
    27. * @param msg 返回内容
    28. */
    29. public AjaxResult(int code, String msg)
    30. {
    31. super.put(CODE_TAG, code);
    32. super.put(MSG_TAG, msg);
    33. }
    34. /**
    35. * 初始化一个新创建的 AjaxResult 对象
    36. *
    37. * @param code 状态码
    38. * @param msg 返回内容
    39. * @param data 数据对象
    40. */
    41. public AjaxResult(int code, String msg, Object data)
    42. {
    43. super.put(CODE_TAG, code);
    44. super.put(MSG_TAG, msg);
    45. if (StringUtils.isNotNull(data))
    46. {
    47. super.put(DATA_TAG, data);
    48. }
    49. }
    50. /**
    51. * 返回成功消息
    52. *
    53. * @return 成功消息
    54. */
    55. public static AjaxResult success()
    56. {
    57. return AjaxResult.success("操作成功");
    58. }
    59. /**
    60. * 返回成功数据
    61. *
    62. * @return 成功消息
    63. */
    64. public static AjaxResult success(Object data)
    65. {
    66. return AjaxResult.success("操作成功", data);
    67. }
    68. /**
    69. * 返回成功消息
    70. *
    71. * @param msg 返回内容
    72. * @return 成功消息
    73. */
    74. public static AjaxResult success(String msg)
    75. {
    76. return AjaxResult.success(msg, null);
    77. }
    78. /**
    79. * 返回成功消息
    80. *
    81. * @param msg 返回内容
    82. * @param data 数据对象
    83. * @return 成功消息
    84. */
    85. public static AjaxResult success(String msg, Object data)
    86. {
    87. return new AjaxResult(HttpStatus.SUCCESS, msg, data);
    88. }
    89. /**
    90. * 返回错误消息
    91. *
    92. * @return
    93. */
    94. public static AjaxResult error()
    95. {
    96. return AjaxResult.error("操作失败");
    97. }
    98. /**
    99. * 返回错误消息
    100. *
    101. * @param msg 返回内容
    102. * @return 警告消息
    103. */
    104. public static AjaxResult error(String msg)
    105. {
    106. return AjaxResult.error(msg, null);
    107. }
    108. /**
    109. * 返回错误消息
    110. *
    111. * @param msg 返回内容
    112. * @param data 数据对象
    113. * @return 警告消息
    114. */
    115. public static AjaxResult error(String msg, Object data)
    116. {
    117. return new AjaxResult(HttpStatus.ERROR, msg, data);
    118. }
    119. /**
    120. * 返回错误消息
    121. *
    122. * @param code 状态码
    123. * @param msg 返回内容
    124. * @return 警告消息
    125. */
    126. public static AjaxResult error(int code, String msg)
    127. {
    128. return new AjaxResult(code, msg, null);
    129. }
    130. /**
    131. * 方便链式调用
    132. *
    133. * @param key 键
    134. * @param value 值
    135. * @return 数据对象
    136. */
    137. @Override
    138. public AjaxResult put(String key, Object value)
    139. {
    140. super.put(key, value);
    141. return this;
    142. }
    143. }

    4. COSUtils
    1. import com.qcloud.cos.COSClient;
    2. import com.qcloud.cos.ClientConfig;
    3. import com.qcloud.cos.auth.BasicCOSCredentials;
    4. import com.qcloud.cos.auth.COSCredentials;
    5. import com.qcloud.cos.http.HttpMethodName;
    6. import com.qcloud.cos.http.HttpProtocol;
    7. import com.qcloud.cos.model.GeneratePresignedUrlRequest;
    8. import com.qcloud.cos.model.ObjectMetadata;
    9. import com.qcloud.cos.model.PutObjectResult;
    10. import com.qcloud.cos.region.Region;
    11. import lombok.extern.slf4j.Slf4j;
    12. import org.springframework.stereotype.Component;
    13. import java.io.IOException;
    14. import java.io.InputStream;
    15. import java.net.URL;
    16. import java.util.Date;
    17. @Slf4j
    18. @Component
    19. public class COSUtils {
    20. // API密钥
    21. private static final String secretId = "xxxxxx";
    22. private static final String secretKey = "xxxxxx";
    23. // 桶名称
    24. private static final String bucketName = "xxxxxx";
    25. // 地域
    26. private static final String region = "xxxxxx";
    27. // 文件夹
    28. private static final String FOLDER = "image/";
    29. public static COSClient getCOSClient() {
    30. // 1 初始化用户身份信息(secretId, secretKey)。
    31. COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    32. // 2 此处设置的地域为香港
    33. Region rg = new Region(region);
    34. ClientConfig clientConfig = new ClientConfig(rg);
    35. // 这里建议设置使用 https 协议
    36. //5.6.54 版本开始,默认使用了 https
    37. clientConfig.setHttpProtocol(HttpProtocol.https);
    38. // 3 生成 cos 客户端。
    39. COSClient cosClient = new COSClient(cred, clientConfig);
    40. return cosClient;
    41. }
    42. public String uploadFileCOS(InputStream instream, String fileName){
    43. String ret = "";
    44. try {
    45. // 创建上传Object的Metadata
    46. ObjectMetadata objectMetadata = new ObjectMetadata();
    47. objectMetadata.setContentLength(instream.available());
    48. objectMetadata.setCacheControl("no-cache");
    49. objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
    50. objectMetadata.setHeader("Pragma", "no-cache");
    51. // 上传文件
    52. PutObjectResult putResult = getCOSClient().putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
    53. ret = putResult.getETag();
    54. } catch (IOException e) {
    55. e.printStackTrace();
    56. }finally {
    57. try {
    58. if (instream != null) {
    59. instream.close();
    60. }
    61. } catch (IOException e) {
    62. e.printStackTrace();
    63. }
    64. }
    65. return ret;
    66. }
    67. public static final String getContentType(String filenameExtension) {
    68. if (filenameExtension.equalsIgnoreCase(".bmp")) {
    69. return "application/x-bmp";
    70. }
    71. if (filenameExtension.equalsIgnoreCase(".gif")) {
    72. return "image/gif";
    73. }
    74. if (filenameExtension.equalsIgnoreCase(".jpeg") ||
    75. filenameExtension.equalsIgnoreCase(".jpg") ||
    76. filenameExtension.equalsIgnoreCase(".png")) {
    77. return "image/jpg";
    78. }
    79. if (filenameExtension.equalsIgnoreCase(".html")) {
    80. return "text/html";
    81. }
    82. if (filenameExtension.equalsIgnoreCase(".txt")) {
    83. return "text/plain";
    84. }
    85. if (filenameExtension.equalsIgnoreCase(".vsd")) {
    86. return "application/vnd.visio";
    87. }
    88. if (filenameExtension.equalsIgnoreCase(".pptx") ||
    89. filenameExtension.equalsIgnoreCase(".ppt")) {
    90. return "application/vnd.ms-powerpoint";
    91. }
    92. if (filenameExtension.equalsIgnoreCase(".docx") ||
    93. filenameExtension.equalsIgnoreCase(".doc")) {
    94. return "application/msword";
    95. }
    96. if (filenameExtension.equalsIgnoreCase(".xla") ||
    97. filenameExtension.equalsIgnoreCase(".xlc") ||
    98. filenameExtension.equalsIgnoreCase(".xlm") ||
    99. filenameExtension.equalsIgnoreCase(".xls") ||
    100. filenameExtension.equalsIgnoreCase(".xlt") ||
    101. filenameExtension.equalsIgnoreCase(".xlw")) {
    102. return "application/vnd.ms-excel";
    103. }
    104. if (filenameExtension.equalsIgnoreCase(".xlsx")) {
    105. return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    106. }
    107. if (filenameExtension.equalsIgnoreCase(".xml")) {
    108. return "text/xml";
    109. }
    110. if (filenameExtension.equalsIgnoreCase(".pdf")) {
    111. return "application/pdf";
    112. }
    113. if (filenameExtension.equalsIgnoreCase(".zip")) {
    114. return "application/zip";
    115. }
    116. if (filenameExtension.equalsIgnoreCase(".tar")) {
    117. return "application/x-tar";
    118. }
    119. if (filenameExtension.equalsIgnoreCase(".avi")) {
    120. return "video/avi";
    121. }
    122. if (filenameExtension.equalsIgnoreCase(".mp4")) {
    123. return "video/mpeg4";
    124. }
    125. if (filenameExtension.equalsIgnoreCase(".mp3")) {
    126. return "audio/mp3";
    127. }
    128. if (filenameExtension.equalsIgnoreCase(".mp2")) {
    129. return "audio/mp2";
    130. }
    131. // 默认下载
    132. // return "application/octet-stream";
    133. return "image/jpg";
    134. }
    135. public String getUrl(String key) {
    136. GeneratePresignedUrlRequest req =
    137. new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
    138. // 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(1小时)
    139. // 10
    140. Date expirationDate = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
    141. req.setExpiration(expirationDate);
    142. COSClient cosClient = getCOSClient();
    143. URL url = cosClient.generatePresignedUrl(req);
    144. cosClient.shutdown();
    145. if (url != null) {
    146. return "https://" + url.getHost() + "/image" + url.getPath();
    147. }
    148. return "";
    149. }
    150. }

    5. 上传成功

  • 相关阅读:
    开源物联网平台ThingsBoard的安装
    ContOS 7 修改IP地址
    Linux常用命令——chpasswd命令
    IO进程间通信:信号
    基于 FFMPEG 的跨平台视频播放器简明教程(三):视频解码
    波奇学Linux:日志
    2019年数维杯数学建模A题 我国省际生态环境与经济交互状况的综合评价求解全过程文档及程序
    【深入浅出 Yarn 架构与实现】6-3 NodeManager 分布式缓存
    第四十五篇,STL标准模板库常见算法
    案例--某站视频爬取
  • 原文地址:https://blog.csdn.net/weixin_43652507/article/details/133752858