• 阿里云OSS存储的应用


    一、普通上传方式

    流程:前端提交上传请求-> gateway -> 转发到上传服务 -> 上传服务将图片流数据传入给对象存储OSS -> OSS 返回一个地址给上传服务 -> 上传服务返回OSS图片存储地址

    缺点:经过服务器,效率减低

    优点:相对安全

    二、服务端签名后直传OSS(推荐)

     流程:  首先把OSS的账号密码存在自己服务器中  -->

                    前端向服务器要到一个Policy  -->

                    服务器利用阿里云的账号密码生成一个 防伪签名(包含访问阿里云的授权令牌,以及要上传阿里云的哪个地址等信息)  -->

                     前端带着 防伪签名 + 带着被上传的文件,上传给阿里云OSS-  -->

                     阿里云验证防伪签名是否正确,正确,上传,失败,不能上传。

    三、上传图片代码

    (1) 原生API

    第一步:导入sdk依赖

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>3.10.2</version>
    </dependency>

     第二步:创建上传类

    1. import com.aliyun.oss.ClientException;
    2. import com.aliyun.oss.OSS;
    3. import com.aliyun.oss.OSSClientBuilder;
    4. import com.aliyun.oss.OSSException;
    5. import java.io.FileInputStream;
    6. import java.io.InputStream;
    7. public class Demo {
    8. public static void main(String[] args) throws Exception {
    9. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    10. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    11. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    12. String accessKeyId = "yourAccessKeyId";
    13. String accessKeySecret = "yourAccessKeySecret";
    14. // 填写Bucket名称,例如examplebucket。
    15. String bucketName = "examplebucket";
    16. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
    17. String objectName = "exampledir/exampleobject.txt";
    18. // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
    19. // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
    20. String filePath= "D:\\localpath\\examplefile.txt";
    21. // 创建OSSClient实例。
    22. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    23. try {
    24. InputStream inputStream = new FileInputStream(filePath);
    25. // 创建PutObject请求。
    26. ossClient.putObject(bucketName, objectName, inputStream);
    27. } catch (OSSException oe) {
    28. System.out.println("Caught an OSSException, which means your request made it to OSS, "
    29. + "but was rejected with an error response for some reason.");
    30. System.out.println("Error Message:" + oe.getErrorMessage());
    31. System.out.println("Error Code:" + oe.getErrorCode());
    32. System.out.println("Request ID:" + oe.getRequestId());
    33. System.out.println("Host ID:" + oe.getHostId());
    34. } catch (ClientException ce) {
    35. System.out.println("Caught an ClientException, which means the client encountered "
    36. + "a serious internal problem while trying to communicate with OSS, "
    37. + "such as not being able to access the network.");
    38. System.out.println("Error Message:" + ce.getMessage());
    39. } finally {
    40. if (ossClient != null) {
    41. ossClient.shutdown();
    42. }
    43. }
    44. }
    45. }

    (2)利用SpringCloud Alibaba-OSS对象存储

    SpringCloud Alibaba-OSS地址        https://github.com/alibaba/spring-cloud-alibaba

    第一步:引入对象存储的starter

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alicloud-oss</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>

    第二步: 配置yml文件

    1. spring:
    2. cloud:
    3. alicloud:
    4. access-key: LTAIdfd5tJdfrG88cuzdsfsdfmgnSeGcLoW
    5. secret-key: DISbdflFkdHW3VsadfnO5gEqgu5Xl0ETrWp7
    6. oss:
    7. endpoint: oss-cn-beijing.aliyuncs.com

    第三步:测试使用

    1. @Autowired
    2. private OSSClient ossClient;
    3. @Test
    4. public void testUpload2(){
    5. try {
    6. InputStream inputStream = new FileInputStream("C:\\Users\\詹姆斯李\\Pictures\\1.jpg");
    7. // 创建PutObject请求。
    8. ossClient.putObject("gulimail-2022-7-2", "1.png", inputStream);
    9. } catch (Exception e) {
    10. e.printStackTrace();
    11. }finally {
    12. if (ossClient != null) {
    13. ossClient.shutdown();
    14. }
    15. }
    16. System.out.println("图片上传成功");
    17. }

    四、服务端签名后直传OSS的实战

    1、拿到后端OSS的签名

    1. // 填写Bucket名称,例如examplebucket。
    2. String bucket = "gulimail-2022-7-2";
    3. // 填写Host地址,格式为https://bucketname.endpoint。
    4. String host = "https:" + bucket + "." + endpoint;
    5. String format = new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
    6. String dir = format+"/";
    7. Map<String, String> respMap = null;
    8. try {
    9. long expireTime = 30;
    10. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
    11. Date expiration = new Date(expireEndTime);
    12. PolicyConditions policyConds = new PolicyConditions();
    13. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
    14. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
    15. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
    16. byte[] binaryData = postPolicy.getBytes("utf-8");
    17. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
    18. String postSignature = ossClient.calculatePostSignature(postPolicy);
    19. respMap = new LinkedHashMap<String, String>();
    20. respMap.put("accessid", accessId);
    21. respMap.put("policy", encodedPolicy);
    22. respMap.put("signature", postSignature);
    23. respMap.put("dir", dir);
    24. respMap.put("host", host);
    25. respMap.put("expire", String.valueOf(expireEndTime / 1000));
    26. } catch (Exception e) {
    27. // Assert.fail(e.getMessage());
    28. System.out.println(e.getMessage());
    29. }
    30. return respMap;
    31. }

    2、前端带着返回的签名,把图片存储到阿里云OSS

  • 相关阅读:
    一幅长文细学JavaScript(一)——一幅长文系列
    基于jeecgboot-vue3的Flowable流程-待办任务(二)
    JavaScript-HTML DOM的用法
    Splunk UBA 之 Kubernetes 证书过期
    C++11标准模板(STL)- 算法(std::partition_point)
    合并报表软件选哪个?这篇文章两分钟告诉你!
    uniapp h5 微信缓存,解决版本更新还是旧版本
    平衡树之B树
    Python实现模块热加载
    [YOLOv7]基于YOLO&Deepsort的车速&车流量检测系统(源码&部署教程)
  • 原文地址:https://blog.csdn.net/qq_45763504/article/details/125572758