java OSS 签名认证直传

安装SDK 

打开概览 ,复制地域节点,作为 String endpoint = ConstantPropertiesUtils.END_POIND

  

复制AccessKey,作为 String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;

复制Secret,作为 String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;

package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    //上传头像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取常量值也可以配置到配置文件@Value(${xxx})获取
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

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

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;

            /**
             * 调用oss方法实现上传
             * 第一个参数  Bucket名称
             * 第二个参数  上传到oss文件路径和文件名称
             * 第三个参数  上传文件输入流
             */
            ossClient.putObject(bucketName, fileName, inputStream);

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

            //需要把上传到阿里云oss路径手动拼接出来
            return  "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

后续补充:上面是原生的SDK做法,使用springboot-starter(推荐) 

        <!--阿里云对象存储OSS-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
            <version>2.2.0.RELEASE</version>
        </dependency>

package com.atguigu.gulimall.thirdparty;

import com.aliyun.oss.OSSClient;
import com.atguigu.gulimall.thirdparty.handler.SmsHandler;
import com.atguigu.gulimall.thirdparty.utils.HttpUtils;
import com.atguigu.gulimall.thirdparty.utils.MyHttpUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.FileInputStream;
import java.io.InputStream;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallThirdPartyApplicationTests {


    @Autowired
    private OSSClient ossClient;


    @Test
    public void ossUploadFile() {
        // 填写Object完整路径,完整路径中不能包含Bucket名称
        String objectName = "master.png";
        String filePath = "D:\\picture\\master.png";
        String bucketName = "gulimall-ldj666";

        try {
            InputStream inputStream = new FileInputStream(filePath);
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
package com.atguigu.gulimall.thirdparty.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.atguigu.gulimall.thirdparty.constant.OssConstant;
import com.atguli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * User: ldj
 * Date: 2022/7/25
 * Time: 12:17
 * Description: No Description
 */

@Slf4j
@RefreshScope
@RestController //将响应体数据以json形式返回给前端
public class OssController {

    @Autowired
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

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

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;


    @RequestMapping(value = "/oss/policy", produces = {MediaType.APPLICATION_JSON_VALUE})
    public R policy() {

        Map<String, String> respMap = new LinkedHashMap<String, String>();

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        String host = "https://" + bucket + "." + endpoint;

        String dir = format + "/";

        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.put(OssConstant.ACCESS_ID, accessId);
            respMap.put(OssConstant.POLICY, encodedPolicy);
            respMap.put(OssConstant.SIGNATURE, postSignature);
            respMap.put(OssConstant.DIR, dir);
            respMap.put(OssConstant.HOST, host);
            respMap.put(OssConstant.EXPIRE, String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            log.info("Error:[{}]", e.getMessage());
        }
        return R.ok().put("data", respMap);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值