• SpringCloud阿里云实现OSS


    SpringCloud阿里云实现OSS

    阿里云Github地址

    在启动示例进行演示之前,我们先了解一下如何接入 OSS。

    接入相关操作只需修改 accessKey、secretKey、endpoint 即可。

    修改 pom.xml 文件,引入 aliyun-oss-spring-boot-starter。

    1. <dependency>
    2. <groupId>com.alibaba.cloudgroupId>
    3. <artifactId>aliyun-oss-spring-boot-starterartifactId>
    4. dependency>

    SpringCloud整合的start为下面的

    1. <-- 应该为下面的-->
    2. <dependency>
    3. <groupId>com.alibaba.cloudgroupId>
    4. <artifactId>spring-cloud-starter-alicloud-ossartifactId>
    5. <version>2.2.0.RELEASEversion>
    6. dependency>

    在配置文件中配置 OSS 服务对应的 accessKey、secretKey 和 endpoint。

    1. // application.properties
    2. alibaba.cloud.access-key=your-ak
    3. alibaba.cloud.secret-key=your-sk
    4. alibaba.cloud.oss.endpoint=***

    以阿里云 accessKey、secretKey 为例,获取方式如下。

    i. 在阿里云控制台界面,单击右上角头像,选择 accesskeys,或者直接登录用户信息管理界面:获取相关key信息填入

    使用SpringCloud阿里云封装好的OSSClient直接进行上传

    1. 测试用例
    2. @SpringBootTest
    3. public class TestFor {
    4. @Resource
    5. OSSClient ossClient;
    6. @Test
    7. public void te() throws FileNotFoundException {
    8. FileInputStream inputStream = new FileInputStream("C:\\Users\\Pictures\\903d28ab0e2f4bb59bdf8f7c6fd22fe4.jpg");
    9. ossClient.putObject("gulimall-xuda","903d28ab0e2f4bb59bdf8f7c6fd22fe4.jpg",inputStream);
    10. ossClient.shutdown();
    11. System.out.println("上传完成");
    12. }
    13. }

    注意:如果您使用了阿里云 STS服务 进行短期访问权限管理,则除了 accessKey、secretKey、endpoint 以外,还需配置 securityToken。

    注入 OSSClient 并进行文件下载操作。

    1. @Service
    2. public class YourService {
    3. @Autowired
    4. private OSSClient ossClient;
    5. public void saveFile() {
    6. // download file to local
    7. ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("pathOfYourLocalFile"));
    8. }
    9. }

    说明:直接注入OSSClient 方式通常用于大量文件对象操作的场景。如果仅仅是需要读取文件对象内容,OSS Starter 也支持以 Resource 方式读取文件, 前后端整合进行阿里云OSS

    上传流程阿里云对象存储-服务端签名后直传

    通常我们是前端将图片数据上传到后端再通过后端上传到OSS的,但这样直接使用服务器进行交互会使我们的服务器压力很大,

    因为上传到OSS需要带上key的账户和密码,所以我们可以向服务器上传我们的请求,服务器将OSSkey生成一个签名数据返回给前端,前端将图片与签名数据进行携带直接与阿里云OSS进行交互上传,这样可以更快更节省服务器压力 可以参考下列文档 阿里云OSS服务端签名直传地址 在这里插入图片描述 网关设置

    使用到nacos作为服务注册,gateway网关作为服务分发

    1. spring:
    2. cloud:
    3. nacos:
    4. discovery:
    5. server-addr: 127.0.0.1:8848
    6. gateway:
    7. routes:
    8. - id: test_route
    9. uri: https://www.baidu.com
    10. predicates:
    11. - Query=url,baidu
    12. - id: third_party_route
    13. uri: lb://gulimall-third-party
    14. predicates:
    15. - Path=/api/thirdparty/**
    16. filters:
    17. - RewritePath=/api/thirdparty/(?.*),/$\{segment}
    18. application:
    19. name: gulimall-gateway
    20. server:
    21. port: 89

    网关配置跨域请求权限

    1. package com.xuda.gateway.config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.web.cors.CorsConfiguration;
    5. import org.springframework.web.cors.reactive.CorsWebFilter;
    6. import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
    7. /**
    8. * @author :程序员徐大大
    9. * @description:统一配置跨域请求
    10. * @date :2022-07-19 22:21
    11. */
    12. @Configuration
    13. public class CoresConfigur {
    14. @Bean
    15. public CorsWebFilter corsWebFilter() {
    16. UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    17. CorsConfiguration coresConfiguration = new CorsConfiguration();
    18. //配置跨域
    19. coresConfiguration.addAllowedHeader("*");
    20. coresConfiguration.addAllowedMethod("*");
    21. // coresConfiguration.addAllowedOrigin("*");
    22. //allowedOriginPatterns
    23. coresConfiguration.addAllowedOriginPattern("*");
    24. coresConfiguration.setAllowCredentials(true);
    25. urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",coresConfiguration);
    26. return new CorsWebFilter(urlBasedCorsConfigurationSource);
    27. }
    28. }

    创建第三方OSS项目

    创建yml相关配置

    1. spring:
    2. cloud:
    3. alicloud:
    4. access-key: your-key
    5. secret-key: your-key
    6. oss:
    7. endpoint: oss-cn-shanghai.aliyuncs.com
    8. nacos:
    9. discovery:
    10. server-addr: 127.0.0.1:8848
    11. application:
    12. name: third-party
    13. server:
    14. port: 8900

    编写回调OSS签名密钥代码

    1. package com.xuda.thirdparty.controller;
    2. import com.alibaba.fastjson.JSONObject;
    3. import com.aliyun.oss.OSSClient;
    4. import com.aliyun.oss.common.utils.BinaryUtil;
    5. import com.aliyun.oss.model.MatchMode;
    6. import com.aliyun.oss.model.PolicyConditions;
    7. import com.xuda.common.utils.R;
    8. import org.springframework.beans.factory.annotation.Value;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import javax.annotation.Resource;
    12. import java.text.SimpleDateFormat;
    13. import java.util.Date;
    14. import java.util.LinkedHashMap;
    15. import java.util.Map;
    16. /**
    17. * @author :程序员徐大大
    18. * @description:TODO
    19. * @date :2022-07-21 21:35
    20. */
    21. @RestController
    22. public class OssController {
    23. @Resource
    24. private OSSClient ossClient;
    25. @Value("${spring.cloud.alicloud.oss.endpoint}")
    26. private String endpoint;
    27. @Value("${spring.cloud.alicloud.access-key}")
    28. private String accessId;
    29. @RequestMapping("/oss/policy")
    30. public R policy() {
    31. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    32. // 填写Bucket名称,例如examplebucket。
    33. String bucket = "gulimall-xuda";
    34. // 填写Host地址,格式为https://bucketname.endpoint。
    35. String host = "https://" + bucket + "."+ endpoint;
    36. // 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
    37. // String callbackUrl = "https://192.168.0.0:8888";
    38. // 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
    39. //将日期作为上传的文件夹目录
    40. String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    41. String dir = format+"/";
    42. Map respMap = null;
    43. try {
    44. long expireTime = 30;
    45. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
    46. Date expiration = new Date(expireEndTime);
    47. PolicyConditions policyConds = new PolicyConditions();
    48. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
    49. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
    50. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
    51. byte[] binaryData = postPolicy.getBytes("utf-8");
    52. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
    53. String postSignature = ossClient.calculatePostSignature(postPolicy);
    54. respMap = new LinkedHashMap();
    55. respMap.put("accessid", accessId);
    56. respMap.put("policy", encodedPolicy);
    57. respMap.put("signature", postSignature);
    58. respMap.put("dir", dir);
    59. respMap.put("host", host);
    60. respMap.put("expire", String.valueOf(expireEndTime / 1000));
    61. // respMap.put("expire", formatISO8601Date(expiration));
    62. } catch (Exception e) {
    63. // Assert.fail(e.getMessage());
    64. System.out.println(e.getMessage());
    65. }
    66. return R.ok().put("data",respMap); //创建返回JSON数据封装
    67. }
    68. }

    JSON返回代码

    1. package com.xuda.common.utils;
    2. import org.apache.http.HttpStatus;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. /**
    6. * 返回数据
    7. *
    8. */
    9. public class R extends HashMap<String, Object> {
    10. private static final long serialVersionUID = 1L;
    11. public R() {
    12. put("code", 0);
    13. put("msg", "success");
    14. }
    15. public static R error() {
    16. return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
    17. }
    18. public static R error(String msg) {
    19. return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    20. }
    21. public static R error(int code, String msg) {
    22. R r = new R();
    23. r.put("code", code);
    24. r.put("msg", msg);
    25. return r;
    26. }
    27. public static R ok(String msg) {
    28. R r = new R();
    29. r.put("msg", msg);
    30. return r;
    31. }
    32. public static R ok(Map<String, Object> map) {
    33. R r = new R();
    34. r.putAll(map);
    35. return r;
    36. }
    37. public static R ok() {
    38. return new R();
    39. }
    40. public R put(String key, Object value) {
    41. super.put(key, value);
    42. return this;
    43. }
    44. }

    前端VUE代码示例

    1. <template>
    2. <div>
    3. <el-upload
    4. action="http://gulimall-xuda.oss-cn-shanghai.aliyuncs.com"
    5. :data="dataObj"
    6. list-type="picture"
    7. :multiple="false" :show-file-list="showFileList"
    8. :file-list="fileList"
    9. :before-upload="beforeUpload"
    10. :on-remove="handleRemove"
    11. :on-success="handleUploadSuccess"
    12. :on-preview="handlePreview">
    13. <el-button size="small" type="primary">点击上传el-button>
    14. <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MBdiv>
    15. el-upload>
    16. <el-dialog :visible.sync="dialogVisible">
    17. <img width="100%" :src="fileList[0].url" alt="">
    18. el-dialog>
    19. div>
    20. template>
    21. <script>
    22. import {policy} from './policy' //导入封装的请求地址 ,下面的可以直接加上
    23. /**
    24. import http from '@/utils/httpRequest.js'
    25. export function policy() {
    26. return new Promise((resolve,reject)=>{
    27. http({
    28. url: http.adornUrl("/thirdparty/oss/policy"),
    29. method: "get",
    30. params: http.adornParams({})
    31. }).then(({ data }) => {
    32. resolve(data);
    33. })
    34. });
    35. }
    36. */
    37. import { getUUID } from '@/utils' //为了使用工具导入UUID
    38. /**
    39. //获取uuid,需要的可以加上进行更改
    40. export function getUUID () {
    41. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    42. return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
    43. })
    44. }
    45. */
    46. export default {
    47. name: 'singleUpload',
    48. props: {
    49. value: String
    50. },
    51. computed: {
    52. imageUrl() {
    53. return this.value;
    54. },
    55. imageName() {
    56. if (this.value != null && this.value !== '') {
    57. return this.value.substr(this.value.lastIndexOf("/") + 1);
    58. } else {
    59. return null;
    60. }
    61. },
    62. fileList() {
    63. return [{
    64. name: this.imageName,
    65. url: this.imageUrl
    66. }]
    67. },
    68. showFileList: {
    69. get: function () {
    70. return this.value !== null && this.value !== ''&& this.value!==undefined;
    71. },
    72. set: function (newValue) {
    73. }
    74. }
    75. },
    76. data() {
    77. return {
    78. dataObj: {
    79. policy: '',
    80. signature: '',
    81. key: '',
    82. ossaccessKeyId: '',
    83. dir: '',
    84. host: '',
    85. // callback:'',
    86. },
    87. dialogVisible: false
    88. };
    89. },
    90. methods: {
    91. emitInput(val) {
    92. this.$emit('input', val)
    93. },
    94. handleRemove(file, fileList) {
    95. this.emitInput('');
    96. },
    97. handlePreview(file) {
    98. this.dialogVisible = true;
    99. },
    100. beforeUpload(file) {
    101. let _self = this;
    102. return new Promise((resolve, reject) => {
    103. policy().then(response => {
    104. console.log("响应的数据",response);
    105. _self.dataObj.policy = response.data.policy;
    106. _self.dataObj.signature = response.data.signature;
    107. _self.dataObj.ossaccessKeyId = response.data.accessid;
    108. _self.dataObj.key = response.data.dir +getUUID()+'_${filename}'; //上传所加的目录
    109. _self.dataObj.dir = response.data.dir;
    110. _self.dataObj.host = response.data.host;
    111. resolve(true)
    112. }).catch(err => {
    113. reject(false)
    114. })
    115. })
    116. },
    117. handleUploadSuccess(res, file) {
    118. console.log("上传成功...")
    119. this.showFileList = true;
    120. this.fileList.pop();
    121. this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) });
    122. this.emitInput(this.fileList[0].url);
    123. }
    124. }
    125. }
    126. script>
    127. <style>
    128. style>

  • 相关阅读:
    二十四、【参考素描三大面和五大调】
    docker 构建jar包/vue镜像以及发布
    RabbitMQ简介及安装使用
    力扣 1856. 子数组最小乘积的最大值
    Docker的入门基础和使用
    tf-lite转换记录
    Guava的Service
    ADS2017之S参数仿真
    Blender:对模型着色
    C++异常处理
  • 原文地址:https://blog.csdn.net/LBWNB_Java/article/details/126027875