Loading...

阿里云云存储OSS

学习地址:https://www.bilibili.com/video/BV1np4y1C7Yf?p=61

开通云存储OSS

地址:https://www.aliyun.com/

image-20200930103722401

img

img

img

开发文档

地址:https://help.aliyun.com/document_detail/31947.html

img

image-20200930104351834

创建存储空间Bucket

image-20200930104720657

根据自己需求配置

image-20200930105031698

image-20200930105135208

上传文件测试

img

Java测试OSS

查看文档:https://help.aliyun.com/document_detail/32008.html

安装

本文使用在Maven项目中加入依赖项

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

简单上传

上传文件流

官方实例

// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
InputStream inputStream = new FileInputStream("<yourlocalFile>");
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);

// 关闭OSSClient。
ossClient.shutdown();

外网访问地址

image-20200930110603968

添加AccessKey子用户

image-20200930110833820

image-20200930110918590

创建子用户

image-20200930111319610

image-20200930111424531

添加权限

image-20200930111530900

image-20200930111738742

创建AccessKey

image-20200930112145714

image-20200930112108648

@SpringBootTest
class GulimallProductApplicationTests {
    @Test
    public void testUpload() throws FileNotFoundException {
        // 填写外网访问地址。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限,建议使用RAM子账号进行API访问或日常运维
        String accessKeyId = "LTAI4GEJTHAo9LeyHmJVtiGL";
        String accessKeySecret = "29AlSA7awLuaQDH6Zs9wWsR8Cc1VQr";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = new FileInputStream("C:\\Users\\mobiw\\Desktop\\mobiw.jpg");
        ossClient.putObject("gulimall-nuc", "mobiw.jpg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("上传成功...");
    }
}

SpringCloud Alibaba

地址:https://spring.io/projects/spring-cloud-alibaba

Git:https://github.com/alibaba/spring-cloud-alibaba

OSS官方案例:https://github.com/alibaba/aliyun-spring-boot/tree/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample

引入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>

在application.yml配置

spring:
  cloud:    
    alicloud:
      access-key: LTAI4GEJTHAo9LeyHmJVtiGL
      secret-key: 29AlSA7awLuaQDH6Zs9wWsR8Cc1VQr
      oss:
        endpoint: oss-cn-beijing.aliyuncs.com
        bucket: gulimall-nuc

测试

@SpringBootTest
class GulimallThirdPartyApplicationTests {

    @Autowired
    OSSClient ossClient;

    @Test
    public void testUpload() throws FileNotFoundException {
        // 上传文件流。
        InputStream inputStream = new FileInputStream("C:\\Users\\mobiw\\Desktop\\mobiw.jpg");
        ossClient.putObject("gulimall-nuc", "mobiw.jpg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("上传成功...");
    }
}

服务端签名后直传

地址:https://help.aliyun.com/document_detail/31926.html

AccessKey ID和AcessKey Secret会暴露在前端页面,因此存在严重的安全隐患。因此,OSS提供了服务端签名后直传的方案

p139016

Java开发服务端签名后直传

https://help.aliyun.com/document_detail/91868.html

具体配置细节查看文档->应用服务器核心代码解析

@RestController
public class OssController {

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/oss/policy")
    public R policy() {

        //https://gulimall-nuc.oss-cn-beijing.aliyuncs.com
        String host = "https://" + bucket + "." + endpoint;
        // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        //String callbackUrl = "http://88.88.88.88:8888";
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return R.ok().put("data",respMap);
    }
}

配置跨域

image-20200930144340035

image-20200930144408733

# elmentUI发送上传请求
<el-upload action="http://gulimall-nuc.oss-cn-beijing.aliyuncs.com"></el-upload>
posted @ 2020-09-30 15:02  iniwym  阅读(688)  评论(0编辑  收藏  举报